How to transform Java's date and datetime to unix time

19.12.2015 15:53:09

Don't get me wrong, the new java.time API introduced in Java 8 is great and I use it instead of the old one, but progress doesn't always go forwards. With Java 8 you may have to learn a new way how to transform the unix time (number of milliseconds since 1.1.1970) to LocalDate and LocalDateTime (and vice versa):

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class Main {

	public static void main(String[] args) {
		// how to transform unix time (number of milliseconds since
		// 1.1.1970) to date / date and time
		{
			long millis = 1450539174378L;

			// unix time to java.util.Date (pre Java 8)
			System.out.println(new Date(millis));

			// unix time to java.time.LocalDate (since Java 8)
			LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());
			System.out.println(localDateTime);

			// unix time to java.time.LocalDateTime (since Java 8)
			LocalDate localDate = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault()).toLocalDate();
			System.out.println(localDate);
		}

		// how to transform date to unix time
		{

			// get unix time from java.util.Date (pre Java 8)
			System.out.println(new Date().getTime());

			// get unix time from java.time.LocalDate (since Java 8)
			System.out.println(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli());

			// get unix time from java.time.LocalDateTime (since Java 8)
			System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
		}
	}

}



© Jiri Pinkas | this project on GitHub | related: JavaVids | Maven Central Repository Search | Java školení | Top SQL Blogs | monitored using: sitemonitoring

Top Java Blogs is a Java blog aggregator (with English-written blogs only) focused on Java SE, Java EE, Spring Framework and Hibernate.