java SimpleDateFormat错误地解析给定的时间戳

时间:2017-03-20 14:13:31

标签: java date time timestamp

当我运行以下代码时:

package testframe;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class dates {

    public static void handleLastValueDate()  {

        Timestamp stamp = new Timestamp(1490018838);
        Date date = new Date(stamp.getTime());
         SimpleDateFormat df =  new SimpleDateFormat("yyyy-MM-dd HH:mm");

    }

    public static void main(String[] args) {

        handleLastValueDate();

    }

}

我得到以下结果:1970-01-18 07:53这是不正确的,应该是

GMT: Mon, 20 Mar 2017 12:55:38 GMT
Your time zone: 3/20/2017, 2:55:38 PM GMT+2:00

任何人都可以请我解释为什么会这样吗?我厌倦了使用语言环境,但也没有帮助!我怎样才能看到正确的时间?

感谢。

1 个答案:

答案 0 :(得分:2)

您的代码正在打印 1970-01-18 07:53 ,因为您需要将1490018838乘以1000(毫秒),另一方面,不需要使用TimeStamp,Date类具有重载的构造函数以毫秒为单位记录时间

Date date = new Date(1490019439L * 1000);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
System.out.println(df.format(date));

也要注意这一点。

new Date(1490019439L * 1000)

我正在使用timeStamp作为Long文字,如果你不这样做,那么整数中的溢出就会发生,你将再次得到一个错误的日期......