Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

Convert Epoch seconds to date and time format in Java

I have seconds since 1970 january 1 UTC (Epoch time).

1320105600

I need to convert that seconds into date and time in below format.

Friday,November 4,2011 5:00,AM

How can I achieve this?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In case you're restricted to legacy java.util.Date and java.util.Calendar APIs, you need to take into account that the timestamps are interpreted in milliseconds, not seconds. So you first need to multiply it by 1000 to get the timestamp in milliseconds.

long seconds = 1320105600;
long millis = seconds * 1000;

This way you can feed it to a.o. the constructor of java.util.Date and finally use SimpleDateFormat to convert a java.util.Date to java.lang.String in the desired date format pattern, if necessary with a predefined time zone (otherwise it would use the system default time zone, which is not GMT/UTC per se and thus the formatted time might be off).

Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // Tuesday,November 1,2011 12:00,AM

In case you're already on Java8, there's a LocalDateTime#ofEpochSecond() which allows you to feed epoch seconds directly without the need for multiplying into milliseconds flavor.

LocalDateTime dateTime = LocalDateTime.ofEpochSecond(seconds, 0, ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
String formattedDate = dateTime.format(formatter);
System.out.println(formattedDate); // Tuesday,November 1,2011 12:00,AM

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...