Java 8 LocalDateTime type conversion stuff (String, java.util.Date)

Java 8 LocalDateTime type conversion stuff (String, java.util.Date)

Introduction

Date and Calendar classes have been used as Java date types, but it is recommended to use LocalDateTime / ZonedDateTime classes etc. from Java 8 onwards.

This time, I had the opportunity to use the LocalDateTime class, so I studied it. It turned out that there is no method that can be converted in one shot, and it is not possible to easily convert the type.

This time, I organized String⇔LocalDateTime and java.util.Date⇔LocalDateTime in my own way.

String → LocalDateTime

When using the SimpleDateFormat class

Convert in the flow of String → SimpleDateFormat → Date → LocalDateTime.

    public static LocalDateTime toLocalDateTime(String date, String format) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date formatDate = sdf.parse(date);
        return LocalDateTime.ofInstant(formatDate.toInstant(), ZoneId.systemDefault());
    }

Usage example

    public static void main(String args[]) {
        //Execution result: 2018-05-07T00:00
        System.out.println(toLocalDateTime("2018/05/07", "yyyy/MM/dd"));
    }

When using the DateTimeFormatter class

Unlike SimpleDateFormat, the DateTimeFormatter class does not have to be new. It is necessary to determine the date pattern with the ofPattern method at the time of generation.

Convert in the flow of String → DateTimeFormatter → LocalDateTime. Can be shorter than using SimpleDateFormat.

    public static LocalDateTime toLocalDateTime(String date, String format) {

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
        return LocalDateTime.parse(date, dtf);
    }

Usage example

    public static void main(String args[]) {
        //Execution result: 2018-05-07T10:00
        System.out.println(toLocalDateTime("2018/05/07 10:00:00","yyyy/MM/dd HH:mm:ss"));
    }

However, since it is a LocalDateTime that has a date and time, an error will occur if you do not specify the time.

    public static void main(String args[]) {
        //Execution result: DateTimeParseException
        System.out.println(toLocalDateTime("2018/05/07","yyyy/MM/dd"));
    }

So, if you only need the date, try returning LocalDate, or

    public static LocalDate toLocalDate(String date, String format) {

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format);
        return LocalDate.parse(date, dtf);

    }

After converting to LocalDate, add 0 o'clock to make it LocalDateTime.

    public static LocalDateTime toLocalDateTime(String date, String format) {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return LocalDate.parse(date, dateTimeFormatter).atTime(LocalTime.MIN);

    }

LocalDateTime → String ~~ This can be converted in one shot by using the parse method. ~~ I'm sorry, it's a lie. It can be converted with format method + DateTimeFormatter.

    public static String toStr(LocalDateTime localDateTime, String format) {

        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return localDateTime.format(dateTimeFormatter);

    }

Usage example

    public static void main(String args[]) {
        //Execution result: 2018/05/07
        System.out.println(toStr(LocalDateTime.now(), "yyyy/MM/dd"));
    }

LocalDateTime → java.util.Date Convert in the flow of LocalDateTime → ZonedDateTime → Instant → java.util.Date.

    public static Date toDate(LocalDateTime localDateTime) {
        ZoneId zone = ZoneId.systemDefault();
        ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, zone);
        Instant instant = zonedDateTime.toInstant();
        return Date.from(instant);
    }

Usage example

    public static void main(String args[]) {
        //Execution result: Mon May 07 19:59:32 JST 2018
        System.out.println(toDate(LocalDateTime.now()));
    }

java.util.Date → LocalDateTime

Convert in the flow of Date → Instant → Local Date Time.

    public static LocalDateTime toLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

Usage example

    public static void main(String args[]) {
        // 2018-05-07T19:59:32.139
        System.out.println(toLocalDateTime(new Date()));
    }

Finally

LocalDateTime is difficult to handle. (Small feeling) It may be better to use LocalDate and LocalTime properly. Variables are declared line by line for ease of understanding (for me), but of course it is better to do everything in one line as told in the comments.

public static void main(String args[]) {
    // String→LocalDateTime
    System.out.println(LocalDate.parse("2018/05/07", 
                           DateTimeFormatter.ofPattern("uuuu/MM/dd"))
                       .atTime(LocalTime.MIN));
}

Question

I haven't fully grasped the difference between SimpleDateFormat and DateTimeFormatter, so I will investigate it later.

Recommended Posts

Java 8 LocalDateTime type conversion stuff (String, java.util.Date)
Java type conversion
Java date data type conversion (Date, Calendar, String)
Type conversion from java BigDecimal type to String type
Uri → String, String → Uri type conversion
[Java] Date type conversion
Java type conversion (String, int, Date, Calendar, etc.)
[Java] List type / Array type conversion
[Java] Precautions for type conversion
Java Primer Series (Type Conversion)
[Java] Correct comparison of String type
Java string
Full-width → half-width conversion with Java String (full-width kana → half-width kana)
Regarding String type equivalence comparison in Java
[Easy-to-understand explanation! ] Reference type type conversion in Java
[Java ~ Variable definition, type conversion ~] Study memo
[Java] Data type / string class cheat sheet
Java study # 3 (type conversion and instruction execution)
Notes on operators using Java ~ String type ~
[Java] Convert Object type null to String type
[Basic knowledge of Java] About type conversion
[Java] Calculation mechanism, operators and type conversion
[Introduction to Java] About type conversion (cast, promotion)
[JAVA] Stream type
java.util.Date ⇔ java.time.LocalDateTime conversion
[Java] String padding
[Java] Enumeration type
Java double type
Java string processing
Java-automatic type conversion
Split string (Java)
[Java] Full-width ⇔ half-width conversion
URL to String conversion
[Java] String comparison and && and ||
Java string multiple replacement
[Java, Kotlin] Type Variance
Java class type field
[Note] Java: String search
Type determination in Java
Java study # 1 (typical type)
About Java String class
Leet string conversion program
[Java] About enum type
Endian conversion with JAVA
[Java Bronze] Learning memo (interface, static method, type conversion, etc.)
[Java] How to convert a character string from String type to byte type
I tried to convert a string to a LocalDate type in Java