I\'m trying to convert a millisecond time (milliseconds since Jan 1 1970) to a time in UTC in Java. I\'ve seen a lot of other questions that utilize SimpleDateFormat to chan
Try below..
package com.example;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TestClient {
/**
* @param args
*/
public static void main(String[] args) {
long time = 1427723278405L;
SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(new Date(time)));
}
}
You can use the new java.time package built into Java 8 and later.
You can create a ZonedDateTime corresponding to that instant in time in UTC timezone:
ZonedDateTime utc = Instant.ofEpochMilli(1427723278405L).atZone(ZoneOffset.UTC);
System.out.println(utc);
You can also use a DateTimeFormatter if you need a different format, for example:
System.out.println( DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss").format(utc));
You May check this..
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(1427723278405L);
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setCalendar(calendar);
System.out.println(formatter.format(calendar.getTime()));
formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(formatter.format(calendar.getTime()));