How to use Java’s new time API

Time:2020-1-13

Before reading this article, please read the summary of machine time, UTC time and local time in the previous article.

There are three particularly important classes in Java’s new time API: instant, localdatetime, zonedatetime. They correspond to the time concepts mentioned in the previous article: machine time, local time without time zone, and local time in time zone.

Machine time can actually be understood as another form of UTC time, which can uniquely determine a certain time on the timeline.

Local time without time zone because there is no time zone information, it cannot uniquely determine a certain time on the time line.

Sometimes, the local time of a region is actually based on UTC time plus some time offset, so it can only determine a certain time on the timeline.

In fact, Java’s new time API is implemented around these three classes. Therefore, a thorough understanding of the purpose and usage scenarios of these three classes is very important for flexible use of Java’s new time API.

Let’s use an example to explain how to use Java’s new time API.

  • Obtain the date and year of the current time.
static void t1() {
  LocalDateTime ldt = LocalDateTime.now();
  System.out.println(ldt.getYear());

  ZonedDateTime zdt = ZonedDateTime.now();
  System.out.println(zdt.getYear());

  //For obtaining the human time information of the current time (mm / DD / yyyy, HHM / s)
  //Using localdatetime or zonedatetime is the same
  //Their bottom layer is to get the machine time first, and then according to their time zone
  //Convert machine time to human time
  //The only difference between zoneddatetime and localdatetime is that they carry time zone information
  //But if it's just to get the information like MM DD YY, the time zone is useless
}
  • Obtain the date of a certain machine time and other information.
static void t2() {
  long millis = System.currentTimeMillis();
  Instant instant = Instant.ofEpochMilli(millis);

  LocalDateTime ldt = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
  System.out.println(ldt.getYear());

  ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, ZoneId.systemDefault());
  System.out.println(zdt.getYear());

  //Machine time can only be used by Java's new time API after it is converted to an instant instance
}
  • Human time to machine time.
static void t3() {
  //Because localdatetime does not have time zone information, it cannot be converted to machine time directly
  //Only by actively providing time zone information
  LocalDateTime ldt = LocalDateTime.now();
  long millis = ldt.toInstant(ZoneOffset.of("+08:00")).toEpochMilli();
  System.out.println(millis);

  //Since the zonedatetime has time zone information, it can be directly converted to machine time
  ZonedDateTime zdt = ZonedDateTime.now();
  millis = zdt.toInstant().toEpochMilli();
  System.out.println(millis);

  //It should also be noted that the class representing human time is not directly converted to machine time, but indirectly completed through the instant class
}
  • Parse the time string.
static void t4() {
  //The parsed string cannot have time zone information
  LocalDateTime ldt = LocalDateTime.parse("2019-09-25T16:32:42");
  System.out.println(ldt);

  //The parsed string must have time zone information
  ZonedDateTime zdt = ZonedDateTime.parse("2019-09-25T16:32:42+08:00");
  System.out.println(zdt);
}
  • Operation of time.
static void t5() {
  //Local datetime's time addition and subtraction is pure addition and subtraction
  LocalDateTime ldt = LocalDateTime.parse("2019-03-10T01:59:59");
  System. Out. Println (LDT. Plushours (1). Gethour()); // output: 2

  //The time addition and subtraction of zonedatetime also considers the time zone information
  //For example, from March to 10t02:00:00, 2019, daylight saving time will be implemented in the United States
  //Their local time will be set back one hour, i.e. 2:00 a.m. to 3:00 a.m
  //For more information about daylight saving time, see the following article:
  // https://en.wikipedia.org/wiki/Daylight_saving_time
  ZonedDateTime zdt = ldt.atZone(ZoneId.of("America/New_York"));
  System. Out. Println (ZDT. Plushours (1). Gethour()); // output: 3

  //So, if time operation is involved, use zonedatetime
}
  • Gets the machine time at zero on the day a machine time belongs to.
static long startOfDay(long millis) {
  return LocalDate.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault())
      .atStartOfDay(ZoneId.systemDefault())
      .toInstant()
      .toEpochMilli();
}
  • Get the machine time of Monday zero of the week that a machine time belongs to.
static long startOfWeek(long millis) {
  return LocalDate.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault())
      .atStartOfDay(ZoneId.systemDefault())
      .with(DayOfWeek.MONDAY)
      .toInstant()
      .toEpochMilli();
}
  • Obtain the machine time at zero on the first day of the month in which a machine time belongs.
static long startOfMonth(long millis) {
  return LocalDate.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault())
      .atStartOfDay(ZoneId.systemDefault())
      .withDayOfMonth(1)
      .toInstant()
      .toEpochMilli();
}

Well, there are so many examples. I think everyone here has almost understood.

For more information about the Java new time API, please refer to the official Java Tutorial:

https://docs.oracle.com/javas…

I hope it can help you.

Finish.

For more original articles, please pay attention to my WeChat public address:

How to use Java's new time API

Recommended Today

Codable: implement JSON in swift like JS

Codable: implement JSON in swift like JS Official document on codable implementation: https://developer.apple.com/documentation/foundation/archives_ and_ serialization/encoding_ and_ decoding_ custom_ types imagejsThe same,iOS 11After that,swiftIt can also be used convenientlyjsonIt’s time to pass the data. To usejson, the class you operate on needs to be implementedCodableInterfaceFoundationAll classes in have been implementedCadableSo if you don’t have some custom […]