Date and time
LocalDate
Create a LocalDate object and read its value
// According to the date of establishment LocalDate date1 = LocalDate.of(2014, 3, 18); // read System.out.println(date1.getYear()); // 2014 System.out.println(date1.getMonth()); // MARCH System.out.println(date1.getMonth().getValue()); // 3 System.out.println(date1.getDayOfMonth()); // 18 System.out.println(date1.lengthOfMonth()); // 31 System.out.println(date1.isLeapYear()); // false // current date LocalDate now = LocalDate.now(); System.out.println(now); // 2018-08-14 // Get date from date object System.out.println(now.get(ChronoField.YEAR)); // 2018 System.out.println(now.get(ChronoField.MONTH_OF_YEAR)); // 8 System.out.println(now.get(ChronoField.DAY_OF_MONTH)); // 14
LocalTime
Create LocalTime and read value
// Create time based on hours, minutes and seconds LocalTime time1 = LocalTime.of(13, 45, 20); System.out.println(time1.getHour()); // 13 System.out.println(time1.getMinute()); // 45 System.out.println(time1.getSecond()); // 20 // Create a date or time from a date or time string LocalDate date2 = LocalDate.parse("2014-03-18"); LocalTime time2 = LocalTime.parse("13:45:20");
LocalDateTime
Create a LocalDateTime object directly or by merging dates and times
// Direct creation date time LocalDateTime lt1 = LocalDateTime.of(2014, Month.MARCH, 18, 13, 45, 20); // Created by date and time LocalDate date1 = LocalDate.of(2014, 3, 18); LocalTime time1 = LocalTime.of(13, 45, 20); LocalDateTime lt2 = LocalDateTime.of(date1, time1); LocalDateTime lt3 = date1.atTime(13, 45, 20); LocalDateTime lt4 = date1.atTime(time1); LocalDateTime lt5 = time1.atDate(date1); // Extract date and time from datetime LocalDate date2 = lt1.toLocalDate(); LocalTime time2 = lt1.toLocalTime();
Instant
Date and time format of the machine
// Get the current time stamp System.out.println(Instant.now().toEpochMilli()); // 1534255959679
Time slot
Duration & Period
The unit of interval is hour, minute and second, and the unit of interval is year, month and day
Create Duration and Period objects
LocalDate date1 = LocalDate.parse("2018-08-12"); LocalDate date2 = LocalDate.parse("2018-08-11"); LocalTime time1 = LocalTime.parse("12:45:20"); LocalTime time2 = LocalTime.parse("12:45:21"); Instant instant1 = Instant.ofEpochSecond(22); Instant instant2 = Instant.ofEpochSecond(11); // Time interval is time seconds Duration d2 = Duration.between(time1, time2); // time2 - time1 Duration d3 = Duration.between(instant1, instant2); // instant2 - instant1 Duration d4 = Duration.ofMinutes(3); // Create a 3 minute time period System.out.println(d2.getSeconds()); // 1 System.out.println(d4.getSeconds()); // 180 // Time interval is MM DD YY Period p1 = Period.between(date1, date2); // date2 - date1 Period p2 = Period.ofDays(10); System.out.println(p1.getDays()); // -1 System.out.println(p2.getDays()); // 10
Manipulating, parsing, and formatting dates
Modify LocalDate object properties
LocalDate date1 = LocalDate.of(2014, 3, 18); // Modify in a more intuitive way LocalDate date1 = date1.withYear(2011); // Revision year LocalDate date1 = date1.withMonth(11); // Revision month LocalDate date1 = date1.withDayOfMonth(25); // Revision date // Modify in a relative way date1.minusYears(1); // Reduction of 1 years date1.plusYears(2); // Plus two years date1.plus(3, ChronoUnit.MONTHS); // Plus March date1.plus(22, ChronoUnit.DAYS); // Plus 22 days
TemporalAdjuster
LocalDate date1 = LocalDate.of(2014, 3, 18); // The first Sunday after the current date including the current date System.out.println(date1.with(nextOrSame(DayOfWeek.SUNDAY))); // 2014-03-23 // First Sunday of the month System.out.println(date1.with(firstInMonth(DayOfWeek.SUNDAY))); // 2014-03-02 // Last Sunday of the month System.out.println(date1.with(lastInMonth(DayOfWeek.SUNDAY))); // 2014-03-30 // First day of the month System.out.println(date1.with(firstDayOfMonth())); // 2014-03-01 // Last day of the month System.out.println(date1.with(lastDayOfMonth())); // 2014-03-31 // The first day of the year System.out.println(date1.with(firstDayOfYear())); // 2014-01-01 // The first day of next year System.out.println(date1.with(firstDayOfNextYear())); // 2015-01-01
Customize a temporaladjuster
Next working day
If the current date is from Sunday to Thursday, move the date back 1 day If the current date is Friday or Saturday, move to next Monday
Scheme 1: implement a TemporalAdjuster class
public class NextWorkingDay implements TemporalAdjuster { @Override public Temporal adjustInto(Temporal temporal) { // What day of the week is the current date DayOfWeek dow = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); // Judge how many days to move back int dayToAdd = 1; if (dow == DayOfWeek.FRIDAY) dayToAdd = 3; else if (dow == DayOfWeek.SATURDAY) dayToAdd = 2; return temporal.plus(dayToAdd, ChronoUnit.DAYS); } }
Scheme 2: use Lambda directly
LocalDate nextWorkingDate = LocalDate.now() .with(temporal -> { // What day of the week is the current date DayOfWeek dow = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); // Judge how many days to move back int dayToAdd = 1; if (dow == DayOfWeek.FRIDAY) dayToAdd = 3; else if (dow == DayOfWeek.SATURDAY) dayToAdd = 2; return temporal.plus(dayToAdd, ChronoUnit.DAYS); });
Scheme 3: using Lambda to implement a TemporalAdjuster
TemporalAdjuster nextWorkingDay = TemporalAdjusters.ofDateAdjuster( temporal -> { // What day of the week is the current date DayOfWeek dow = DayOfWeek.of(temporal.get(ChronoField.DAY_OF_WEEK)); // Judge how many days to move back int dayToAdd = 1; if (dow == DayOfWeek.FRIDAY) dayToAdd = 3; else if (dow == DayOfWeek.SATURDAY) dayToAdd = 2; return temporal.plus(dayToAdd, ChronoUnit.DAYS); } );
Output and analyze date and time objects
LocalDate date1 = LocalDate.of(2014, 3, 18); System.out.println(date1.format(DateTimeFormatter.BASIC_ISO_DATE)); // 20140318 System.out.println(date1.format(DateTimeFormatter.ISO_LOCAL_DATE)); // 2014-03-18 LocalDate date2 = LocalDate.parse("20140318", DateTimeFormatter.BASIC_ISO_DATE); LocalDate date3 = LocalDate.parse("2014-03-18", DateTimeFormatter.ISO_LOCAL_DATE); // Create a DateTimeFormatter based on a pattern DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); System.out.println(date1.format(formatter)); // 2014/03/18 LocalDate date4 = LocalDate.parse("2018/08/14", formatter); // Create a localized DateTimeFormatter DateTimeFormatter italianFormatter = DateTimeFormatter.ofPattern("d. MMMM yyyy", Locale.ITALIAN); System.out.println(date1.format(italianFormatter)); // 18. marzo 2014 LocalDate date5 = LocalDate.parse("18. marzo 2014", italianFormatter);
Time zone and calendar
ZoneId
// Print all time zones ZoneId.getAvailableZoneIds().stream() .forEach(System.out::println); // Create a time zone in the format {region} / {City} ZoneId romeZone = ZoneId.of("Europe/Rome"); // Convert old time zone object to ZoneId ZoneId newZoneId = TimeZone.getDefault().toZoneId(); // Get current time zone ZoneId defaultZoneId = ZoneId.systemDefault(); System.out.println(defaultZoneId); // Asia/Shanghai
ZonedDateTime
Add time zone information for a point in time
ZoneId romeZone = ZoneId.of("Europe/Rome"); // Add time zone information for a point in time LocalDate date1 = LocalDate.now(); ZonedDateTime zdt1 = date1.atStartOfDay(romeZone); LocalDateTime dateTime1 = LocalDateTime.now(); ZonedDateTime zdt2 = dateTime1.atZone(romeZone); Instant instant1 = Instant.now(); ZonedDateTime zdt3 = instant1.atZone(romeZone); // Convert LocalDateTime to Instant Instant instantFromDateTime = dateTime1.toInstant(ZoneOffset.ofHours(0)); // Convert Instant to LocalDateTime LocalDateTime dateTimeFromInstant = LocalDateTime.ofInstant(instant1, romeZone);
ZoneOffset
Time zone calculation using a fixed deviation from UTC / Greenwich mean time
// Not recommended // New York is five hours behind London ZoneOffset newYorkOffset = ZoneOffset.of("-05:00"); System.out.println(newYorkOffset); OffsetDateTime dateTimeInNewYork = OffsetDateTime.of(LocalDateTime.now(), newYorkOffset);
Other calendar systems
ISO-8601 calendar system is the fact standard of world civilization calendar system. Java 8 also provides four other calendar systems, namely
ThaiBuddhistDate MinguoDate JapaneseDate HijrahDate // Islamic calendar
All these classes and LocalDate implement the chronololocaldate interface.
LocalDate date1 = LocalDate.now(); JapaneseDate japaneseDate = JapaneseDate.from(date1); System.out.println(japaneseDate); // Japanese Heisei 30-08-14 Chronology japaneseChronology = Chronology.ofLocale(Locale.JAPAN); ChronoLocalDate now = japaneseChronology.dateNow(); System.out.println(now); // 2018-08-14