Date manipulation in Java 8

In Java8, LocalDate, LocalTime and LocalDateTime classes have been added. Thanks to that, the troublesome date operation has become easier at once, so I would like to introduce it.

Current time

python


LocalDateTime ldt = LocalDateTime.now();

Now you can get it easily.

Create an instance by specifying the date numerically

You can create an instance by specifying the year, month, date, hour, minute, second, and nanosecond as numerical values.

python


LocalDateTime ldt = LocalDateTime.of(2017, 12, 10, 23, 59, 59, 1);

Of course, if you specify 13 or more for the month and a date that does not exist in the month, an error will occur.

python


LocalDateTime.of(2017, 13, 10, 23, 59, 59, 1); // ⇒ java.time.DateTimeException
LocalDateTime.of(2017, 12, 32, 23, 59, 59, 1); // ⇒ java.time.DateTimeException
LocalDateTime.of(2017, 12, 10, 24, 59, 59, 1); // ⇒ java.time.DateTimeException

Create an instance by specifying the date in characters

I'm personally most pleased with this feature. It's much easier to parse than ever before. First, use the DateTimeFormatter class to create a formatter by specifying the date format, locale, etc. you want to parse.

python


DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss", Locale.JAPANESE);

Use the formatter you created to parse the date string.

python


DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss", Locale.JAPANESE);
LocalDateTime ldt = LocalDateTime.parse("2017/10/15 13:53:15", dtf);

Of course, if you specify a date that does not exist, an error will occur.

python


DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss", Locale.JAPANESE);
LocalDateTime ldt = LocalDateTime.parse("2017/10/32 13:53:15", dtf);
// ⇒  java.time.DateTimeException: Invalid value for DayOfMonth

This is controlled by an attribute called resolver style that Datetimeformatter has. The resolver style is an attribute that determines how to resolve when the value when parsing the date and time string is out of range (after 32 days in October). The default is SMART (smart), and there are also LENIENT (generous) and STRICT (strict). The following is the operation for each setting.

If it is clearly out of the allowable range, an error will occur. For example, 13th and 32nd are absolutely impossible, so an error. In a month with less than 31 days, if you specify a day less than 31 that is not possible, it will be the last day of the month. Example)

python


DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
        .withResolverStyle(ResolverStyle.SMART);
LocalDateTime ldt = LocalDateTime.parse("2017/11/31 23:16:10", dtf);
// ⇒ 2017/11/30T23:16:10

Even if you specify 31 like this, it will be rounded to 30. By the way, an error will occur even if items other than the date exceed the limit value. Error even if you specify 24:00 instead of 23:00. Error even if 60 minutes is specified.

If it exceeds the permissible range, the date will be the date after the original end of the month and the excess is added. Example)

python


DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss")
        .withResolverStyle(ResolverStyle.LENIENT);
LocalDateTime ldt = LocalDateTime.parse("2017/11/33 23:16:10", dtf);
// ⇒ 2017/12/03T23:16:10
LocalDateTime ldt = LocalDateTime.parse("2017/13/33 24:61:61", dtf);
// ⇒ 2018-02-03T01:02:01

Anything that is not allowed on that date and time will result in an error. Strictly speaking, the format "yyyy" is a year for the calendar (ERA. In the case of the Japanese calendar, Showa or Heisei), so if ERA is not specified, an error will occur. The format "uuuu" represents a year unrelated to ERA. Example)

python


DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd G HH:mm:ss")
        .withLocale(Locale.ENGLISH)
        .withResolverStyle(ResolverStyle.STRICT);
LocalDateTime ldt = LocalDateTime.parse("2017/11/30 AD 23:16:10", dtf);
// ⇒ 2017/11/30T23:16:10

DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss")
        .withResolverStyle(ResolverStyle.STRICT);
LocalDateTime ldt2 = LocalDateTime.parse("2017/11/30 23:16:10", dtf2);

English moon perspective

All you have to do is change the locale.

python


DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MMM/dd HH:mm:ss", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse("2017/Oct/15 13:53:15", dtf);

However, in this case, if you make the month lowercase like "oct", an error will occur. What to do in this case. I'm not sure. Also, I will post it after checking it.

Method of calculation

LocalDate makes it very easy to add and subtract dates. It's just what you see, so I won't explain it.

python


LocalDateTime ldt = LocalDateTime.now();
ldt.plusYears(1);
ldt.plusMonths(1);
ldt.plusDays(1);
ldt.plusHours(1);
ldt.plusMinutes(1);
ldt.plusSeconds(1);
ldt.minusYears(1);
ldt.minusMonths(1);
ldt.minusDays(1);
ldt.minusHours(1);
ldt.minusMinutes(1);
ldt.minusSeconds(1);

Is it like this? Also, if there is a use, we will add it.

Recommended Posts

Date manipulation in Java 8
Java basic date manipulation
View current date in Java
Date processing in Java (LocalDate: Initialization)
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
Pi in Java
FizzBuzz in Java
How to implement date calculation in Java
Studying Java 8 (date API in java.time package)
Output Date in Java in ISO 8601 extended format
How to get the date in java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
"Hello World" in Java
Callable Interface in Java
[Java] Date / time operations
Comments in Java source
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Create JSON in Java
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
java: Add date [Note]
Initializing HashMap in Java
[Java] Date type conversion
Try using RocksDB in Java
Read binary files in Java 1
Avoid Yubaba's error in Java
Get EXIF information in Java
Save Java PDF in Excel
[Neta] Sleep Sort in Java
Edit ini in Java: ini4j
Java history in this world
Let Java segfault in 6 lines
Try developing Spresense in Java (1)
Try functional type in Java! ①
I made roulette in Java.
Create hyperlinks in Java PowerPoint
Implement two-step verification in Java
Write flyway callbacks in Java
Importing Excel data in Java 2