Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

android - Simple Date format gives wrong info from epoch timestamp

I found that this gives a wrong date. but how i can not solve it. please someone help me. I am new in android Development. Thanks in advance;

String timestamp = "1538970640";

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM 'at' hh:mm a z" );
String dateString = formatter.format(new Date(Long.parseLong(timestamp)));

This returns:

19 Jan at 01:29 AM GMT+06:oo

But it should be:

8 Oct at 9:50 AM GMT+06:00
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The java.util.Date constructor accepts milliseconds since the Epoch, not seconds:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

The following code which uses ms is working:

String timestamp = "1538970640000";   // use ms NOT s
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM 'at' hh:mm a z" );
String dateString = formatter.format(new Date(Long.parseLong(timestamp)));

08 Oct at 05:50 AM CEST

Demo

Part of the problem you were facing is that your date format omitted the year component, which was actually coming up as 1970.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...