Simple Date format gives wrong info from epoch timestamp

前端 未结 2 1256
夕颜
夕颜 2020-12-22 01:58

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 = \"15

2条回答
  •  臣服心动
    2020-12-22 02:22

    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.

提交回复
热议问题