We write a Java code to convert LocalDateTime to long (in Milliseconds) using Java 8 date-time API.
Get Milliseconds from LocalDateTime in Java 8
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);
}
}
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);
}
}
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
Continue Learning with Java Guides
Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.
By Ramesh Fadatare - Udemy Instructor Partner
Comments
Post a Comment
Leave Comment