[language] tips for using Java date API

Keywords: Java Programming

preface

In daily development, we often use some date related data operations, such as obtaining the week corresponding to the date, obtaining the existence of a month, etc.

The date API design before Java 8 is very anti-human. For the time created with new Date(), the year is obtained by 1 starting from 1900, and the obtained month 0 represents January. Moreover, thread safety cannot be guaranteed when using, and problems may occur when multiple threads operate.

In Java 8, the Time API is redesigned and clearly separated. It defines different classes for Date, Time, DateTime, unix timestamp and Time zone, and all classes are immutable to ensure thread safety in use.

This paper will explain the commonly used cases in development to facilitate everyone's efficient development.

Core class

The default format of Java 8 date and time is as follows: yyyy-MM-dd-HH-mm-ss.zzz

Several main core classes:

  • LocalDate: represents a date class, excluding time, hour, minute and second
  • LocalTime: represents a time class, excluding date, month, day, year
  • LocalDateTime: represents the date and time class
  • ZonedDateTime: represents the time zone date time class
  • OffsetDateTime: indicates that the date time is obtained by UTC time offset
  • Clock: indicates to obtain the current instantaneous time, date or time in a time zone
  • Instant: indicates Unix time and represents timestamp, such as 2018-01-14T02:20:13.592Z
  • Duration: represents the time between two times, and represents an absolute accurate span, in milliseconds
  • Period: indicates the period between two dates
  • ZoneId: indicates the time zone
  • DateTimeFormatter: indicates formatted output
  • Temporary adjusters: it means to obtain the specified date and time, such as the first day of the current month, the last day of this year, etc

Common cases

Get today's date

Use now() of the LocalDate object to get today's date directly. Then the date can be formatted and printed through DateTimeFormatter.

LocalDate localDate = LocalDate.now();
System.out.println("Today's date is:"+localDate);
DateTimeFormatter fmtDate = DateTimeFormatter.ofPattern("yyyyMMdd");
System.out.println("Format today's date:"+localDate.format(fmtDate));

/**
 * -------- Print--------
 * Today's date is: November 12, 2021
 * Today's date format: 20211112
 */

Get the month, year and day of the date

LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
System.out.println("year:"+year);
System.out.println("month:"+month);
System.out.println("day:"+day);

/**
 * -------- Print--------
 *Year: 2021
 *Month: November
 *Date: 12
 */

Compare different dates

The LocalDate object can compare dates through the equals() / isAfter() / isBefore() methods, which is very convenient.

LocalDate localDate = LocalDate.now();
LocalDate localDateOther = LocalDate.of(2021,11,11);
System.out.println("localDate be equal to localDateOther: "+localDate.equals(localDateOther));
System.out.println("localDate greater than localDateOther: "+localDate.isAfter(localDateOther));
System.out.println("localDate less than localDateOther: "+localDate.isBefore(localDateOther));

/**
 * -------- Print--------
 *localDate Equals localDateOther: false
 *localDate Greater than localDateOther: true
 *localDate Less than localDateOther: false
 */

Get current time

Using now() of the LocalTime object, you can directly get today's time, excluding the date.

LocalTime nowTime = LocalTime.now();
System.out.println("Current time is:"+nowTime);

/**
 * -------- Print--------
 *Current time: 12:56:17.908
 */

Calculation of date and time

Using now() of the LocalTime object, you can directly get today's time, excluding the date.

LocalDate localDate = LocalDate.of(2021,11,11);
LocalTime nowTime = LocalTime.now();
LocalDate tempDate;
LocalTime tempTime;

tempDate = localDate.with(TemporalAdjusters.previous(DayOfWeek.MONDAY)).minusDays(7);
System.out.println("This year's double 11 was last Monday:"+tempDate);

DayOfWeek dayOfWeek = localDate.getDayOfWeek();
System.out.println("What week is double 11 this year?:"+dayOfWeek);

tempTime = nowTime.plusHours(5).plusMinutes(20);
System.out.println("Five hours and 20 minutes later:"+tempTime);

tempTime = nowTime.minusHours(3);
System.out.println("3 Hours ago:"+tempTime);

/**
 * -------- Print--------
 *Last Monday was November 1, 2021
 *What week is double 11 this year THURSDAY
 *Five hours and 20 minutes later: 18:28:44.508
 *3 Hours ago: 10:08:44.508
 */

Calculate the interval between two dates

Using now() of the LocalTime object, you can directly get today's time, excluding the date.

LocalDate localDate = LocalDate.of(2019,5,1);
LocalDate localDateOther = LocalDate.of(2021,11,11);
Period period = Period.between(localDate, localDateOther);
System.out.println("Years:" + period.getYears() +" months:" + period.getMonths() +" days:"+period.getDays());

/**
 * -------- Print--------
 *Years:2 months:6 days:10
 */

summary

Through the use of LocalDate and LocalTime, you can efficiently calculate the time and date of common business scenarios. You'd better do it yourself.

Posted by Rother2005 on Mon, 22 Nov 2021 23:01:18 -0800