Convert LocalDateTime to Long in Java

In this quick article, we will discuss how to convert the LocalDateTime class into long in Java.

We write a Java code to convert LocalDateTime to long (in Milliseconds) using Java 8 date-time API.

As we know, LocalDateTime doesn't contain information about the time zone. In other words, we can't get milliseconds directly from LocalDateTime instance. First, we created an instance of the current date. After that, we used the toEpochMilli() method to convert the ZonedDateTime into milliseconds.

Get Milliseconds from LocalDateTime in Java 8

First, we created an instance of the current date. After that, we used the toEpochMilli() method to convert the ZonedDateTime into milliseconds.
package com.java.tutorials.collections;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

/**
 * Convert LocalDateTime to long
 * @author Ramesh Fadatare
 *
 */
public class LocalDateTimeExample {
    public static void main(String[] args) {
  
        LocalDateTime localDateTime = LocalDateTime.now();
  
        ZonedDateTime zdt = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
        long date = zdt.toInstant().toEpochMilli();
  
        System.out.println(date);
    }
}
Output:
1584458975530

Add Day, Hour and Minute to LocalDateTime

package com.java.tutorials.collections;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class LocalDateTimeExample {
 public static void main(String[] args) {
  
     LocalDateTime dateTime = LocalDateTime.now();;
     System.out.println(dateTime);
     
     // add days
     dateTime = dateTime.plusDays(10L);
     System.out.println(dateTime);
  
     // add hours
     dateTime = dateTime.plusHours(10L);
     System.out.println(dateTime);
  
     // add minutes
     dateTime.plusMinutes(10L);
     System.out.println(dateTime);
  
     ZonedDateTime zonedDateTime = ZonedDateTime.of(dateTime, ZoneId.systemDefault());
     long date = zonedDateTime.toInstant().toEpochMilli();

     System.out.println(date);
 }
}
Output:
2020-03-17T21:01:36.501682600
2020-03-27T21:01:36.501682600
2020-03-28T07:01:36.501682600
2020-03-28T07:01:36.501682600
1585359096501

References

Comments