1

我正在尝试将事件时间戳转换为日期,我的代码:

Calendar c = Calendar.getInstance();
c.setTimeInMillis(event.timestamp/1000000);//time in ms (timestamp is in ns)
System.out.println((new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")).format(c.getTime()));

我怎么会得到 1970-01-02?

4

1 回答 1

4

我假设您正在使用SensorEvent.timestamp。文档没有提到这是自上次启动以来以纳秒为单位的唤醒时间(类似于SystemClock.uptimeMillis()),而不是自 Unix 纪元以来的时间。简而言之,您的设备似乎已经唤醒了不到两天。

此外,Calendar.getTime()返回一个 Date 对象,并且有一个 Date 构造函数,它需要毫秒,因此您可以缩短代码:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(new Date(event.timestamp / 1000000)));
于 2012-08-26T16:12:00.877 回答