In this article, we will discuss about newly introduced LocalDateTime class in Java 1.8 version for dealing with date and time in program with ease and convenience.
Prior to introducing LocalDate, LocalTime and LocalDateTime in Java 1.8 version, we have to deal with java.util.Date, java.util.Calendar, java.sql.Timestamp, java.sql.Time, java.util.TimeZone for date/time handling in Java which isn’t easy & straight-forward and there are few issues as mentioned below,
- Thread-safety :- Existing Date/Time classes and its methods aren’t thread-safe and hence it’s not convenient to handle in concurrent/parallel environment
- Not so-easy API design :- Existing Date/Time classes’ methods aren’t convenient to use in day-to-day programmer’s coding or development
- Time-zone settings :- Developers or Programmer’s life becomes difficult while dealing with time zone settings in programs
Let’s move forward and discuss about java.time.LocalDateTime introduced in Java 1.8 version
1. LocalDateTime :
- There are 3 ways to get/form a LocalDateTime,
- First is to get current system date/time using static factory method now()
- Second is to form a LocalDateTime using static factory method of() passing year, month, day, hour, minute, second and nano information
- Third and final is to parse date/time in String-form to LocalDateTime using static factory method parse()
- The fully qualified package/class name of LocalDateTime is java.time.LocalDateTime i.e.; LocalDateTime is present under java.time package
- Class declaration for LocalDateTime is as follows,
package java.time;
public final class LocalDateTime
implements Temporal, TemporalAdjuster, ChronoLocalDateTime<LocalDate>, Serializable {
}
2. LocalDateTime methods or APIs :
Important LocalDateTime method details,
- now() – get current date-time from the system clock in the default time-zone
- of() – get an instance of LocalDateTime from a year, month, day, hour, minute, second and nanoseconds passed
- parse() – get an instance of LocalDateTime from a text string in yyyy-MM-ddTHH:mm:ss.nnn or yyyy-MM-ddTHH:mm:ss or yyyy-MM-ddTHH:mm formats (there are 9 variants)
- getYear() – get the Year field from LocalDateTime
- getMonthValue() – get the month-of-year field from 1 to 12 from LocalDateTime
- getMonth() – get the month-of-year field using the
Month
enum from LocalDateTime - getDayOfMonth() – get the day-of-month field from LocalDateTime
- getDayOfWeek() – get the day-of-week field, which is an enum
DayOfWeek
from LocalDateTime - getDayOfYear() – get the day-of-year field from LocalDateTime
- getHour() – get the hour-of-day field from LocalDateTime
- getMinute() – get the minute-of-hour field from LocalDateTime
- getSecond() – get the second-of-minute field from LocalDateTime
- getNano() – get the nano-of-second field from LocalDateTime
- plusDays() – Returns a copy of this
LocalDateTime
with the specified number of days added - plusWeeks() – Returns a copy of this
LocalDateTime
with the specified number of weeks added - plusMonths() – Returns a copy of this
LocalDateTime
with the specified number of months added - plusYears() – Returns a copy of this
LocalDateTime
with the specified number of years added - plusNanos() – Returns a copy of this
LocalDateTime
with the specified number of nanoseconds added - plusSeconds() – Returns a copy of this
LocalDateTime
with the specified number of seconds added - plusMinutes() – Returns a copy of this
LocalDateTime
with the specified number of minutes added - plusHours() – Returns a copy of this
LocalDateTime
with the specified number of hours added - minusDays() – Returns a copy of this
LocalDateTime
with the specified number of days subtracted - minusWeeks() – Returns a copy of this
LocalDateTime
with the specified number of weeks subtracted - minusMonths() – Returns a copy of this
LocalDateTime
with the specified number of months subtracted - minusYears() – Returns a copy of this
LocalDateTime
with the specified number of years subtracted - minusNanos() – Returns a copy of this
LocalDateTime
with the specified number of nanoseconds subtracted - minusSeconds() – Returns a copy of this
LocalDateTime
with the specified number of seconds subtracted - minusMinutes() – Returns a copy of this
LocalDateTime
with the specified number of minutes subtracted - minusHours() – Returns a copy of this
LocalDateTime
with the specified number of hours subtracted - format() – Formats invoking
LocalDateTime
using the specified date formatter - withDayOfMonth() – Returns a copy of this
LocalDateTime
with the day-of-month altered - withMonth() – Returns a copy of this
LocalDateTime
with the month-of-year altered - withYear() – Returns a copy of this
LocalDateTime
with the year altered - withHour() – Returns a copy of this
LocalDateTime
with the hour-of-day altered - withMinute() – Returns a copy of this
LocalDateTime
with the minute-of-hour altered - withSecond() – Returns a copy of this
LocalDateTime
with the second-of-minute altered - withNano() – Returns a copy of this
LocalDateTime
with the nano-of-second altered - isBefore(ChronoLocalDateTime) – checks if the invoking LocalDateTime is before the specified LocalDateTime
- isAfter(ChronoLocalDateTime) – checks if invoking LocalDateTime is after the specified LocalDateTime
- atZone(ZoneId) – Combines invoking LocalDateTime with a time-zone to create a ZonedDateTime
- atOffset(ZoneOffset) – Combines invoking LocalDateTime with an offset to create an OffsetDateTime
- toInstant(ZoneOffset) – Converts invoking LocalDateTime/ChronoLocalDateTime to an Instant
- toLocalDate()- gets the LocalDate part of the invoking LocalDateTime
- toLocalTime() – gets the LocalTime part of the invoking LocalDateTime
- isSupported(TemporalField) – checks if the specified field is supported by invoking LocalDateTime and returns boolean value true/false
- isSupported((TemporalUnit) – checks if the specified unit is supported by invoking LocalDateTime and returns boolean value true/false
3. LocalDateTime examples :
- LocalDateTime.now() – get current date/time from system clock
- LocalDateTime.of() – form LocalDateTime passing Year, Month, Day, Hour, Minute, Second and Nano fields
- LocalDateTime.parse() – parse the date/time in String-form to LocalDateTime
- Adding day, week, month and year to LocalDateTime using plusDays(), plusWeeks(), plusMonths() and plusYears() methods respectively
- Adding nano, second, minute and hour to LocalDateTime using plusNanos(), plusSeconds(), plusMinutes() and plusHours() methods respectively
- Subtracting day, week, month and year from LocalDateTime using minusDays(), minusWeeks(), minusMonths() and minusYears() methods respectively
- Subtracting nano, second, minute and hour from LocalDateTime using minusNanos(), minusSeconds(), minusMinutes() and minusHours() methods respectively
- Formatting LocalDateTime in different formats using DateTimeFormatter class
- Altering day, month, year, nano, second, minute and hour fields of LocalDateTime using withDayOfMonth(), withMonth(), withYear(), withNano(), withSecond(), withMinute() and withHour() methods respectively
- Check LocalDateTime is Before/After another LocalDateTime using below methods,
- isBefore(ChronoLocalDateTime) – checks if the invoking LocalDateTime is before the specified LocalDateTime
- isAfter(ChronoLocalDateTime) – Checks if invoking LocalDateTime is after the specified LocalDateTime
- Convert LocalDateTime to ZonedDateTime/OffsetDateTime/Instant/LocalDate/LocalTime
- Check Temporal Field supported by LocalDateTime using isSupported() method
- Check Temporal Unit supported by LocalDateTime using isSupported() method
3.1 LocalDateTime.now() method – get Current System Date/time
- LocalDateTime.now() method helps to get current system date/time which will be in the yyyy-MM-ddTHH:mm:ss.nnn format
- We can get year, month, day, hour, minute, second and nano-second field/part from LocalDateTime using different methods mentioned above and then we can form our own format as required like “dd.MM.yyyy HH:mm:ss.nnn“
- Read Java 8 – How to get Date and Time fields from LocalDateTime ? for more details and examples
LocalDateTimeExampleUsingNowMethod.java
package in.bench.resources.localdatetime.sorting;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
public class LocalDateTimeExampleUsingNowMethod {
public static void main(String[] args) {
// get current system date along with time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Today's local date/time is = " + localDateTime);
// 1. Date part
System.out.println("\n1. Date part from LocalDateTime : \n");
// 1.1 get YEAR part from current system date
int year = localDateTime.getYear();
System.out.println("Year is : " + year);
// 1.2 get MONTH part from current system date
int month = localDateTime.getMonthValue();
System.out.println("Month is : " + month);
// 1.3 get MONTH part from current system date
Month monthInWords = localDateTime.getMonth();
System.out.println("Month in Words is : " + monthInWords);
// 1.4 get DAY part from current system date
int day = localDateTime.getDayOfMonth();
System.out.println("Day is : " + day);
// 1.5 get DAY part from current system date
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();
System.out.println("Day of Week is : " + dayOfWeek);
// 1.6 get DAY part from current system date
int dayOfYear = localDateTime.getDayOfYear();
System.out.println("Day of Year is : " + dayOfYear);
// 2. Time part
System.out.println("\n2. Time part from LocalDateTime : \n");
// 2.1 get HOUR value from current system time
int hours = localDateTime.getHour();
System.out.println("Hour is : " + hours);
// 2.2 get MINUTE value from current system time
int minutes = localDateTime.getMinute();
System.out.println("Minutes is : " + minutes);
// 2.3 get SECOND value from current system time
int seconds = localDateTime.getSecond();
System.out.println("Seconds is : " + seconds);
// 2.4 get NANO SECOND value from current system time
int nano = localDateTime.getNano();
System.out.println("Nano Seconds is : " + nano);
}
}
Output:
Today's local date/time is = 2022-06-23T19:32:48.179955500
1. Date part from LocalDateTime :
Year is : 2022
Month is : 6
Month in Words is : JUNE
Day is : 23
Day of Week is : THURSDAY
Day of Year is : 174
2. Time part from LocalDateTime :
Hour is : 19
Minutes is : 32
Seconds is : 48
Nano Seconds is : 179955500
3.2 LocalDateTime.of() method – form Date/time
- Passing year, month, day, hour, minute, second and nano-second fields/parts to LocalDateTime.of() method returns LocalDateTime which will be in the yyyy-MM-ddTHH:mm:ss.nnn format
- We can extract different fields like year, month, day, hour, minute, second and nanosecond from LocalDateTime and then form our own format as required like “dd/MM/yyyy HH:mm:ss.nnn“
- Read more in the below articles,
LocalDateTimeExampleUsingOfMethod.java
package in.bench.resources.localdatetime.sorting;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
public class LocalDateTimeExampleUsingOfMethod {
public static void main(String[] args) {
// for specific date along with time
LocalDateTime dateTime = LocalDateTime.of(1950, Month.JANUARY, 26, 11, 45, 37, 987000000);
System.out.println("Date/time is = " + dateTime);
// 1. Date part
System.out.println("\nDate part from LocalDateTime :- \n");
// 1.1 get YEAR part from current system date
int year = dateTime.getYear();
System.out.println("1. Year is : " + year);
// 1.2 get MONTH part from current system date
int month = dateTime.getMonthValue();
System.out.println("2. Month is : " + month);
// 1.3 get MONTH part from current system date
Month monthInWords = dateTime.getMonth();
System.out.println("3. Month in Words is : " + monthInWords);
// 1.4 get DAY part from current system date
int day = dateTime.getDayOfMonth();
System.out.println("4. Day is : " + day);
// 1.5 get DAY part from current system date
DayOfWeek dayOfWeek = dateTime.getDayOfWeek();
System.out.println("5. Day of Week is : " + dayOfWeek);
// 1.6 get DAY part from current system date
int dayOfYear = dateTime.getDayOfYear();
System.out.println("6. Day of Year is : " + dayOfYear);
// 2. Time part
System.out.println("\n2. Time part from LocalDateTime :- \n");
// 2.1 get HOUR value from current system time
int hours = dateTime.getHour();
System.out.println("1. Hour is : " + hours);
// 2.2 get MINUTE value from current system time
int minutes = dateTime.getMinute();
System.out.println("2. Minutes is : " + minutes);
// 2.3 get SECOND value from current system time
int seconds = dateTime.getSecond();
System.out.println("3. Seconds is : " + seconds);
// 2.4 get NANO value from current system time
int nano = dateTime.getNano();
System.out.print("4. Nano is : " + nano);
}
}
Output:
Date/time is = 1950-01-26T11:45:37.987
Date part from LocalDateTime :-
1. Year is : 1950
2. Month is : 1
3. Month in Words is : JANUARY
4. Day is : 26
5. Day of Week is : THURSDAY
6. Day of Year is : 26
2. Time part from LocalDateTime :-
1. Hour is : 11
2. Minutes is : 45
3. Seconds is : 37
4. Nano is : 987000000
3.3 LocalDateTime.parse() method – get Date/time in String-form
- Sometimes, we need to parse date/time passed in String-form to LocalDateTime, for that we can use LocalDateTime.parse() method which will return LocalDateTime in yyyy-MM-ddTHH:mm:ss.nnn format
- While parsing Date/Time, value in String-form should be in either of the below formats only, otherwise java.time.format.DateTimeParseException will be thrown
- yyyy-MM-ddTHH:mm:ss.nnn
- yyyy-MM-ddTHH:mm:ss
- yyyy-MM-ddTHH:mm
- Read more in the below articles,
LocalDateTimeExampleUsingParseMethod.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
public class LocalDateTimeExampleUsingParseMethod {
public static void main(String[] args) {
// 1. LocalDateTime with all fields y, M, d, H, m, s, n
String dateTimeInStr1 = "1950-01-26T11:17:39.987654321";
// 1.1 convert/parse to dateInString to LocalDateTime
LocalDateTime dateTime1 = LocalDateTime.parse(dateTimeInStr1);
System.out.println("1. Parsed date time is - " + dateTime1);
// 2. LocalDateTime with fields y, M, d, H, m, s
String dateTimeInStr2 = "1999-07-23T07:43:27";
// 2.1 convert/parse to dateInString to LocalDateTime
LocalDateTime dateTime2 = LocalDateTime.parse(dateTimeInStr2);
System.out.println("2. Parsed date time is - " + dateTime2);
// 3. LocalDateTime with fields y, M, d, H, m
String dateTimeInStr3 = "2022-06-23T05:30";
// 3.1 convert/parse to dateInString to LocalDateTime
LocalDateTime dateTime3 = LocalDateTime.parse(dateTimeInStr3);
System.out.println("3. Parsed date time is - " + dateTime3);
}
}
Output:
1. Parsed date time is - 1950-01-26T11:17:39.987654321
2. Parsed date time is - 1999-07-23T07:43:27
3. Parsed date time is - 2022-06-23T05:30
3.4 Adding Day/Week/Month/Year to LocalDateTime :
- Add 5 Days to current system LocalDateTime using plusDays() method
- Add 2 Weeks to current system LocalDateTime using plusWeeks() method
- Add 3 Months to current system LocalDateTime using plusMonths() method
- Add 1 Year to current system LocalDateTime using plusYears() method
- Read Java 8 – How to add Date and Time fields to LocalDateTime ? for more details and examples
AddDatePartToLocalDateTime.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
public class AddDatePartToLocalDateTime {
public static void main(String[] args) {
// 1. get current system date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current System Date/time is = " + localDateTime);
// 1.1 add 5 days with current system date/time
LocalDateTime add_5_Days = localDateTime.plusDays(5);
System.out.println("\n1. After adding 5 Days to Current System Date/time is = "
+ add_5_Days);
// 1.2 add 2 weeks to current system date/time
LocalDateTime add_2_Weeks = localDateTime.plusWeeks(2);
System.out.println("2. After adding 2 Weeks to Current System Date/time is = "
+ add_2_Weeks);
// 1.3 add 3 months to current system date/time
LocalDateTime add_3_Months = localDateTime.plusMonths(3);
System.out.println("3. After adding 3 Months to Current System Date/time is = "
+ add_3_Months);
// 1.4 add 1 year to current system date/time
LocalDateTime add_1_Year = localDateTime.plusYears(1);
System.out.print("4. After adding 1 Year to Current System Date/time is = "
+ add_1_Year);
}
}
Output:
Current System Date/time is = 2022-08-11T17:52:26.947164200
1. After adding 5 Days to Current System Date/time is = 2022-08-16T17:52:26.947164200
2. After adding 2 Weeks to Current System Date/time is = 2022-08-25T17:52:26.947164200
3. After adding 3 Months to Current System Date/time is = 2022-11-11T17:52:26.947164200
4. After adding 1 Year to Current System Date/time is = 2023-08-11T17:52:26.947164200
3.5 Adding Nano/Second/Minute/Hour to LocalDateTime :
- Add 125 Nanos to current system LocalDateTime using plusNanos() method
- Add 37 Seconds to current system LocalDateTime using plusSeconds() method
- Add 19 Minutes to current system LocalDateTime using plusMinutes() method
- Add 5 Hours to current system LocalDateTime using plusHours() method
- Read Java 8 – How to add Date and Time fields to LocalDateTime ? for more details and examples
AddTimePartToLocalDateTime.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
public class AddTimePartToLocalDateTime {
public static void main(String[] args) {
// 1. get current system Date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current System Date/time is - " + localDateTime);
// 1.1 add 125 NanoSeconds to current system Date/time
LocalDateTime add_125_Nanos = localDateTime.plusNanos(125);
System.out.println("\n1. After adding 125 Nano Seconds to Current System Date/time is - "
+ add_125_Nanos);
// 1.2 add 37 Seconds to current system Date/time
LocalDateTime add_37_Seconds = localDateTime.plusSeconds(37);
System.out.println("2. After adding 37 Seconds to Current System Date/time is - "
+ add_37_Seconds);
// 1.3 add 19 Minutes to current system Date/time
LocalDateTime add_19_Minutes = localDateTime.plusMinutes(19);
System.out.println("3. After adding 19 Minutes to Current System Date/time is - "
+ add_19_Minutes);
// 1.4 add 5 Hours to current system Date/time
LocalDateTime add_5_Hours = localDateTime.plusHours(5);
System.out.print("4. After adding 5 Hours to Current System Date/time is - "
+ add_5_Hours);
}
}
Output:
Current System Date/time is - 2022-08-11T17:53:34.428550800
1. After adding 125 Nano Seconds to Current System Date/time is - 2022-08-11T17:53:34.428550925
2. After adding 37 Seconds to Current System Date/time is - 2022-08-11T17:54:11.428550800
3. After adding 19 Minutes to Current System Date/time is - 2022-08-11T18:12:34.428550800
4. After adding 5 Hours to Current System Date/time is - 2022-08-11T22:53:34.428550800
3.6 Subtracting Day/Week/Month/Year from LocalDateTime :
- Subtract 5 Days from current system LocalDateTime using minusDays() method
- Subtract 2 Weeks from current system LocalDateTime using minusWeeks() method
- Subtract 3 Months from current system LocalDateTime using minusMonths() method
- Subtract 1 Year from current system LocalDateTime using minusYears() method
- Read Java 8 – How to subtract Date and Time fields from LocalDateTime ? for more details and examples
SubtractDatePartFromLocalDateTime.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
public class SubtractDatePartFromLocalDateTime {
public static void main(String[] args) {
// 1. get current system Date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current System Date/time is - " + localDateTime);
// 1.1 subtract 5 days from current system Date/time
LocalDateTime subtract_5_Days = localDateTime.minusDays(5);
System.out.println("\n1. After subtracting 5 Days from Current System Date/time is - "
+ subtract_5_Days);
// 1.2 subtract 2 weeks from current system Date/time
LocalDateTime subtract_2_Weeks = localDateTime.minusWeeks(2);
System.out.println("2. After subtracting 2 Weeks from Current System Date/time is - "
+ subtract_2_Weeks);
// 1.3 subtract 3 months from current system Date/time
LocalDateTime subtract_3_Months = localDateTime.minusMonths(3);
System.out.println("3. After subtracting 3 Months from Current System Date/time is - "
+ subtract_3_Months);
// 1.4 subtract 1 year from current system Date/time
LocalDateTime subtract_1_Year = localDateTime.minusYears(1);
System.out.print("4. After subtracting 1 Year from Current System Date/time is - "
+ subtract_1_Year);
}
}
Output:
Current System Date/time is - 2022-08-11T17:54:39.261392900
1. After subtracting 5 Days from Current System Date/time is - 2022-08-06T17:54:39.261392900
2. After subtracting 2 Weeks from Current System Date/time is - 2022-07-28T17:54:39.261392900
3. After subtracting 3 Months from Current System Date/time is - 2022-05-11T17:54:39.261392900
4. After subtracting 1 Year from Current System Date/time is - 2021-08-11T17:54:39.261392900
3.7 Subtracting Nano/Second/Minute/Hour from LocalDateTime :
- Subtract 125 Nanos from current system LocalDateTime using minusNanos() method
- Subtract 37 Seconds from current system LocalDateTime using minusSeconds() method
- Subtract 19 Minutes from current system LocalDateTime using minusMinutes() method
- Subtract 5 Hours from current system LocalDateTime using minusHours() method
- Read Java 8 – How to subtract Date and Time fields from LocalDateTime ? for more details and examples
SubtractTimePartFromLocalDateTime.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
public class SubtractTimePartFromLocalDateTime {
public static void main(String[] args) {
// 1. get current system Date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current System Date/time is - " + localDateTime);
// 1.1 subtract 125 NanoSeconds from current system Date/time
LocalDateTime sub_125_Nanos = localDateTime.minusNanos(125);
System.out.println("\n1. After subtracting 125 Nano Seconds from Current System Date/time is - "
+ sub_125_Nanos);
// 1.2 subtract 37 Seconds from current system Date/time
LocalDateTime sub_37_Seconds = localDateTime.minusSeconds(37);
System.out.println("2. After subtracting 37 Seconds from Current System Date/time is - "
+ sub_37_Seconds);
// 1.3 subtract 19 Minutes from current system Date/time
LocalDateTime sub_19_Minutes = localDateTime.minusMinutes(19);
System.out.println("3. After subtracting 19 Minutes from Current System Date/time is - "
+ sub_19_Minutes);
// 1.4 subtract 5 Hours from current system Date/time
LocalDateTime sub_5_Hours = localDateTime.minusHours(5);
System.out.print ("4. After subtracting 5 Hours from Current System Date/time is - "
+ sub_5_Hours);
}
}
Output:
Current System Date/time is - 2022-08-11T17:55:36.736538500
1. After subtracting 125 Nano Seconds from Current System Date/time is - 2022-08-11T17:55:36.736538375
2. After subtracting 37 Seconds from Current System Date/time is - 2022-08-11T17:54:59.736538500
3. After subtracting 19 Minutes from Current System Date/time is - 2022-08-11T17:36:36.736538500
4. After subtracting 5 Hours from Current System Date/time is - 2022-08-11T12:55:36.736538500
3.8 Formatting LocalDateTime using DateTimeFormatter:
- We can convert default ISO_LOCAL_DATE_TIME (LocalDateTime) format yyyy-MM-ddTHH:mm:ss.nnn to any other formats using LocalDateTime.format() method by passing DateTimeFormatter class as argument with required pattern in String-form
- In this illustration, we are using 5 different custom formats as listed below,
- DateTimeFormatter.ofPattern(“dd.MM.yyyy“)
- DateTimeFormatter.ofPattern(“dd-MMM-yyyy“)
- DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm“)
- DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss“)
- DateTimeFormatter.ofPattern(“dd-MM-yyyy HH:mm:ss.nnn“)
- Read more in the below articles,
FormattingLocalDateTimeUsingFormatMethod.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class FormattingLocalDateTimeUsingFormatMethod {
public static void main(String[] args) {
// 1. get current system Date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current Date/time in ISO_LOCAL_DATE_TIME format is = "
+ localDateTime);
// 1.1 format LocalDateTime to dd.MM.yyyy
String formattedDate = localDateTime.format(DateTimeFormatter
.ofPattern("dd.MM.yyyy"));
System.out.println("\n1. Current Date/time in dd.MM.yyyy format is = "
+ formattedDate);
// 1.2 format LocalDateTime to dd-MMM-yyyy
String formattedDate2 = localDateTime.format(DateTimeFormatter
.ofPattern("dd-MMM-yyyy"));
System.out.println("2. Current Date/time in dd-MMM-yyyy format is = "
+ formattedDate2);
// 1.3 format LocalDateTime to dd-MM-yyyy HH:mm
String formattedDate3 = localDateTime.format(DateTimeFormatter
.ofPattern("dd-MM-yyyy HH:mm"));
System.out.println("3. Current Date/time in dd-MM-yyyy HH:mm format is = "
+ formattedDate3);
// 1.4 format LocalDateTime to dd-MM-yyyy HH:mm:ss
String formattedDate4 = localDateTime.format(DateTimeFormatter
.ofPattern("dd-MM-yyyy HH:mm:ss"));
System.out.println("4. Current Date/time in dd-MM-yyyy HH:mm:ss format is = "
+ formattedDate4);
// 1.5 format LocalDateTime to dd-MM-yyyy HH:mm:ss.nnn
String formattedDate5 = localDateTime.format(DateTimeFormatter
.ofPattern("dd-MM-yyyy HH:mm:ss.nnn"));
System.out.print("5. Current Date/time in dd-MM-yyyy HH:mm:ss.nnn format is = "
+ formattedDate5);
}
}
Output:
Current Date/time in ISO_LOCAL_DATE_TIME format is = 2022-08-11T17:58:09.818508
1. Current Date/time in dd.MM.yyyy format is = 11.08.2022
2. Current Date/time in dd-MMM-yyyy format is = 11-Aug-2022
3. Current Date/time in dd-MM-yyyy HH:mm format is = 11-08-2022 17:58
4. Current Date/time in dd-MM-yyyy HH:mm:ss format is = 11-08-2022 17:58:09
5. Current Date/time in dd-MM-yyyy HH:mm:ss.nnn format is = 11-08-2022 17:58:09.818508000
3.9 Altering Day/Month/Year & Nano/Second/Minute/Hour fields with LocalDateTime:
- Altering Day, Month, Year, Hour, Minute, Second and Nano-second field/part of LocalDateTime is possible with the help below methods,
- withDayOfMonth() – This method alters day-of-month part/field of the invoking LocalDateTime
- withMonth() – This method alters month-of-year part/field of the invoking LocalDateTime
- withYear() – This method alters year part/field of the invoking LocalDateTime
- withHour() – This method alters hour part/field of the invoking LocalDateTime
- withMinute() – This method alters minute part/field of the invoking LocalDateTime
- withSecond() – This method alters second part/field of the invoking LocalDateTime
- withNano() -This method alters nano-second part/field of the invoking LocalDateTime
- Read Java 8 – How to alter Date and Time fields of LocalDateTime ? for more details and examples
AlterLocalDateTime.java
package in.bench.resources.java8.localdatetime.examples;
import java.time.LocalDateTime;
public class AlterLocalDateTime {
public static void main(String[] args) {
// get Current System Date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current Date/time in ISO_LOCAL_DATE_TIME format is = "
+ localDateTime);
// 1. Altering Day/Month/Year parts of LocalDateTime
System.out.println("\nAltering Day/Month/Year parts of LocalDateTime :- \n");
// 1.1 alter/change/modify DAY part of Current System Date/time
LocalDateTime dateAltered = localDateTime.withDayOfMonth(15);
System.out.println("1. Day (15) altered in Current System Date/time is = "
+ dateAltered);
// 1.2 alter/change/modify MONTH part of Current System Date/time
LocalDateTime monthAltered = localDateTime.withMonth(9);
System.out.println("2. Month (9) altered in Current System Date/time is = "
+ monthAltered);
// 1.3 alter/change/modify YEAR part of Current System Date/time
LocalDateTime yearAltered = localDateTime.withYear(2023);
System.out.println("3. Year (2023) altered in Current System Date/time is = "
+ yearAltered);
// 2. Altering Nano/Second/Minute/Hour from LocalDateTime
System.out.println("\nAltering Nano/Second/Minute/Hour parts of LocalDateTime :- \n");
// 2.1 alter/change/modify HOUR part to Current System Date/time
LocalDateTime hourAltered = localDateTime.withHour(5);
System.out.println("1. Hours (5) altered in Current System Date/time is = "
+ hourAltered);
// 2.2 alter/change/modify MINUTE part to current system Date/time
LocalDateTime minuteAltered = localDateTime.withMinute(19);
System.out.println("2. Minutes (19) altered in Current System Date/time is = "
+ minuteAltered);
// 2.3 alter/change/modify SECOND part to current system Date/time
LocalDateTime secondAltered = localDateTime.withSecond(47);
System.out.println("3. Seconds (47) altered in Current System Date/time is = "
+ secondAltered);
// 2.4 alter/change/modify NANOSECOND part to current system Date/time
LocalDateTime nanoAltered = localDateTime.withNano(125);
System.out.print("4. Nanoseconds (125) altered in Current System Date/time is = "
+ nanoAltered);
}
}
Output:
Current Date/time in ISO_LOCAL_DATE_TIME format is = 2022-08-11T18:00:25.518879900
Altering Day/Month/Year parts of LocalDateTime :-
1. Day (15) altered in Current System Date/time is = 2022-08-15T18:00:25.518879900
2. Month (9) altered in Current System Date/time is = 2022-09-11T18:00:25.518879900
3. Year (2023) altered in Current System Date/time is = 2023-08-11T18:00:25.518879900
Altering Nano/Second/Minute/Hour parts of LocalDateTime :-
1. Hours (5) altered in Current System Date/time is = 2022-08-11T05:00:25.518879900
2. Minutes (19) altered in Current System Date/time is = 2022-08-11T18:19:25.518879900
3. Seconds (47) altered in Current System Date/time is = 2022-08-11T18:00:47.518879900
4. Nanoseconds (125) altered in Current System Date/time is = 2022-08-11T18:00:25.000000125
3.10 Check LocalDateTime is Before/After another LocalDateTime :
- isBefore(ChronoLocalDateTime) – checks if the invoking LocalDateTime is before the specified LocalDateTime
- Read Java 8 – How to check whether a LocalDateTime is Before another LocalDateTime ? for more details and examples
- isAfter(ChronoLocalDateTime) – checks if invoking LocalDateTime is after the specified LocalDateTime
- Read Java 8 – How to check whether a LocalDateTime is After another LocalDateTime ? for more details and examples
- Read Java 8 – How to compare two LocalDateTime instances ? to learn how to compare 2 instances of LocalDateTime
Compare2LocalDateTime.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
import java.time.Month;
public class Compare2LocalDateTime {
public static void main(String[] args) {
// 1. get Current Date/time
LocalDateTime todaysLocalDateTime = LocalDateTime.of(2022, Month.AUGUST, 11, 12, 30, 30, 500);
System.out.println("1. Current Date/time is = " + todaysLocalDateTime);
// 2. form Past Date/time
LocalDateTime pastLocalDateTime = LocalDateTime.of(2022, Month.AUGUST, 11, 1, 1, 1, 100);
System.out.println("2. Past Date/time is = " + pastLocalDateTime);
// 3. form Future Date/time
LocalDateTime futureLocalDateTime = LocalDateTime.of(2022, Month.AUGUST, 11, 23, 59, 59, 200);
System.out.println("3. Future Date/time is = " + futureLocalDateTime);
// 4. isBefore() - LocalDateTime comparison
System.out.println("\n\n4. Comparing 2 LocalDateTime using isBefore() method :- \n");
// 4.1 check whether todaysLocalDateTime isBefore futureLocalDateTime
boolean isBefore1 = todaysLocalDateTime.isBefore(futureLocalDateTime);
System.out.println("4.1 Current Date/time (" + todaysLocalDateTime
+ ") \n\t\t is Before Future Date/time (" + futureLocalDateTime + ") ? "
+ isBefore1);
// 4.2 check whether todaysLocalDateTime isBefore pastLocalDateTime
boolean isBefore2 = todaysLocalDateTime.isBefore(pastLocalDateTime);
System.out.println("4.2 Current Date/time (" + todaysLocalDateTime
+ ") \n\t\t is Before Past Date/time (" + pastLocalDateTime + ") ? "
+ isBefore2);
// 5. isAfter() - LocalDateTime comparison
System.out.println("\n\n5. Comparing 2 LocalDateTime using isAfter() method :- \n");
// 5.1 check whether todaysLocalDateTime isAfter futureLocalDateTime
boolean isAfter1 = todaysLocalDateTime.isAfter(futureLocalDateTime);
System.out.println("5.1 Current Date/time (" + todaysLocalDateTime
+ ") \n\t\t is After Future Date/time (" + futureLocalDateTime + ") ? "
+ isAfter1);
// 5.2 check whether todaysLocalDateTime isAfter pastLocalDateTime
boolean isAfter2 = todaysLocalDateTime.isAfter(pastLocalDateTime);
System.out.print("5.2 Current Date/time (" + todaysLocalDateTime
+ ") \n\t\t is After Past Date/time (" + pastLocalDateTime + ") ? "
+ isAfter2);
}
}
Output:
1. Current Date/time is = 2022-08-11T12:30:30.000000500
2. Past Date/time is = 2022-08-11T01:01:01.000000100
3. Future Date/time is = 2022-08-11T23:59:59.000000200
4. Comparing 2 LocalDateTime using isBefore() method :-
4.1 Current Date/time (2022-08-11T12:30:30.000000500)
is Before Future Date/time (2022-08-11T23:59:59.000000200) ? true
4.2 Current Date/time (2022-08-11T12:30:30.000000500)
is Before Past Date/time (2022-08-11T01:01:01.000000100) ? false
5. Comparing 2 LocalDateTime using isAfter() method :-
5.1 Current Date/time (2022-08-11T12:30:30.000000500)
is After Future Date/time (2022-08-11T23:59:59.000000200) ? false
5.2 Current Date/time (2022-08-11T12:30:30.000000500)
is After Past Date/time (2022-08-11T01:01:01.000000100) ? true
3.11 LocalDateTime to ZonedDateTime/OffsetDateTime/Instant or LocalDate/LocalTime :
- atZone(ZoneId) – Combines invoking LocalDateTime with a time-zone to create a ZonedDateTime
- Read Java 8 – How to convert LocalDateTime to ZonedDateTime ? for more details and examples
- atOffset(ZoneOffset) – Combines invoking LocalDateTime with an offset to create an OffsetDateTime
- Read Java 8 – How to convert LocalDateTime to an OffsetDateTime ? for more details and examples
- toInstant(ZoneOffset) – Converts invoking LocalDateTime/ChronoLocalDateTime to an Instant
- Read Java 8 – How to convert LocalDateTime to an Instant ? for more details and examples
- toLocalDate()- gets the LocalDate part of the invoking LocalDateTime
- toLocalTime() – gets the LocalTime part of the invoking LocalDateTime
- Read Java 8 – How to extract LocalDateTime and LocalTime from LocalDateTime ? for more details and examples
- Read below articles for more conversion,
- Java 8 – How to convert LocalDateTime to java.util.Date and vice-versa ?
- Java 8 – How to convert LocalDateTime to java.sql.Timestamp and vice-versa ?
- Java 8 – How to convert LocalDateTime to Calendar and vice-versa ?
- Java 8 – How to convert LocalDateTime to GregorianCalendar and vice-versa ?
- Java 8 – How to convert LocalDateTime to XMLGregorianCalendar and vice-versa ?
- Java 8 – How to convert java.util.Date to LocalDateTime in different ways ?
ConvertLocalDateTime.java
package in.bench.resources.localdatetime.sorting;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class ConvertLocalDateTime {
public static void main(String[] args) {
// 1. get current System Date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current System Date/time is = " + localDateTime);
// 2. get system default zone
ZoneId zoneId = ZoneId.systemDefault();
System.out.println("Default System Zone is = " + zoneId);
// 3. get system default zone offset
ZoneOffset zoneOffset = ZoneOffset.of("+05:30");
System.out.println("Zone Offset is = " + zoneOffset);
// 4. convert LocalDateTime to ZonedDateTime using atZone(ZoneId)
ZonedDateTime zonedDateTime = localDateTime.atZone(zoneId);
System.out.println("\nConversion of LocalDateTime to ZonedDateTime is :- \n"
+ zonedDateTime);
// 5. convert LocalDateTime to OffsetDateTime using atOffset(zoneOffset)
OffsetDateTime offsetDateTime = localDateTime.atOffset(zoneOffset);
System.out.println("\nConversion of LocalDateTime to OffsetDateTime is :- \n"
+ offsetDateTime);
// 6. convert LocalDateTime to an Instant using toInstant(zoneOffset)
Instant instant = localDateTime.toInstant(zoneOffset);
System.out.println("\nConversion of LocalDateTime to Instant is :- \n"
+ instant);
// 7. get LocalDate from LocalDateTime
LocalDate localDate = localDateTime.toLocalDate();
System.out.println("\nConversion of LocalDateTime to LocalDate is :- \n"
+ localDate);
// 8. get LocalTime from LocalDateTime
LocalTime localTime = localDateTime.toLocalTime();
System.out.print("\nConversion of LocalDateTime to LocalTime is :- \n"
+ localTime);
}
}
Output:
Current System Date/time is = 2022-08-11T19:03:54.309566300
Default System Zone is = Asia/Calcutta
Zone Offset is = +05:30
Conversion of LocalDateTime to ZonedDateTime is :-
2022-08-11T19:03:54.309566300+05:30[Asia/Calcutta]
Conversion of LocalDateTime to OffsetDateTime is :-
2022-08-11T19:03:54.309566300+05:30
Conversion of LocalDateTime to Instant is :-
2022-08-11T13:33:54.309566300Z
Conversion of LocalDateTime to LocalDate is :-
2022-08-11
Conversion of LocalDateTime to LocalTime is :-
19:03:54.309566300
3.12 Check Temporal Fields supported by LocalDateTime :
- isSupported(TemporalField) – checks if the specified field is supported by invoking LocalDateTime and returns boolean value true/false
- Read Java 8 – What are all the Temporal Fields supported by LocalDateTime ? for more details and examples
CheckLocalDateTimeIsSupportedUsingTemporalField.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
import java.time.temporal.ChronoField;
public class CheckLocalDateTimeIsSupportedUsingTemporalField {
public static void main(String[] args) {
// get current system date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current system date/time is = " + localDateTime);
// 1. check ChronoField.NANO_OF_SECOND field supported ?
System.out.println("\n1. LocalDateTime.isSupported(ChronoField.NANO_OF_SECOND) ? " +
localDateTime.isSupported(ChronoField.NANO_OF_SECOND));
// 2. check ChronoField.DAY_OF_MONTH field supported ?
System.out.println("\n2. LocalDateTime.isSupported(ChronoField.DAY_OF_MONTH) ? " +
localDateTime.isSupported(ChronoField.DAY_OF_MONTH));
// 3. check ChronoField.INSTANT_SECONDS field supported ?
System.out.print("\n3. LocalDateTime.isSupported(ChronoField.INSTANT_SECONDS) ? " +
localDateTime.isSupported(ChronoField.INSTANT_SECONDS));
}
}
Output:
Current system date/time is = 2022-08-11T19:17:20.152996800
1. LocalDateTime.isSupported(ChronoField.NANO_OF_SECOND) ? true
2. LocalDateTime.isSupported(ChronoField.DAY_OF_MONTH) ? true
3. LocalDateTime.isSupported(ChronoField.INSTANT_SECONDS) ? false
3.13 Check Temporal Units supported by LocalDateTime :
- isSupported((TemporalUnit) – checks if the specified unit is supported by invoking LocalDateTime and returns boolean value true/false
- Read Java 8 – What are all the Temporal Units supported by LocalDateTime ? for more details and examples
CheckLocalDateTimeIsSupportedUsingTemporalUnit.java
package in.bench.resources.localdatetime.sorting;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class CheckLocalDateTimeIsSupportedUsingTemporalUnit {
public static void main(String[] args) {
// get current system date/time
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println("Current system date/time is = " + localDateTime);
// 1. check ChronoUnit.NANOS field supported ?
System.out.println("\n1. LocalDateTime.isSupported(ChronoUnit.NANOS) ? " +
localDateTime.isSupported(ChronoUnit.NANOS));
// 2. check ChronoUnit.DAYS field supported ?
System.out.println("\n2. LocalDateTime.isSupported(ChronoUnit.DAYS) ? " +
localDateTime.isSupported(ChronoUnit.DAYS));
// 3. check ChronoUnit.FOREVER field supported ?
System.out.print("\n3. LocalDateTime.isSupported(ChronoUnit.FOREVER) ? " +
localDateTime.isSupported(ChronoUnit.FOREVER));
}
}
Output:
Current system date/time is = 2022-08-11T19:18:39.346165
1. LocalDateTime.isSupported(ChronoUnit.NANOS) ? true
2. LocalDateTime.isSupported(ChronoUnit.DAYS) ? true
3. LocalDateTime.isSupported(ChronoUnit.FOREVER) ? false
Related Articles:
- Java 8 – LocalDate with method details and examples
- Java 8 – LocalTime with method details and examples
- Java 8 – LocalDateTime with method details and examples
- Java 8 – ZonedDateTime with method details and examples
- Java 8 – Display all Zones and its Offset using ZoneId and ZoneOffset
- Java 8 – OffsetDateTime with method details and examples
- Java 8 – Instant with method details and examples
- Java 8 – How to display Zones for particular Offset ?
- Java 8 – Clock with method details and examples
- Java 8 – OffsetTime with method details and examples
- Java 8 – Period with method details and examples
- Java 8 – Duration with method details and examples
- Java 8 – How to get current Date and Time ?
- More Java 8 Date/Time API examples
References:
- https://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
- https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/ZoneId.html
- https://docs.oracle.com/javase/8/docs/api/java/time/ZoneOffset.html
- https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html
- https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html
- https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Date.html
- https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
- https://docs.oracle.com/javase/7/docs/api/java/sql/Timestamp.html
- https://docs.oracle.com/javase/7/docs/api/java/sql/Time.html
Happy Coding !!
Happy Learning !!