SimpleDateFormat始终以错误的时区返回1970.01.17 [英] SimpleDateFormat always returns 1970.01.17 with wrong timezone

查看:162
本文介绍了SimpleDateFormat始终以错误的时区返回1970.01.17的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Processing 3.0,并且当我的Arduino输出某些值时,我试图打印一个简单的时间戳,但是它不起作用。我尝试使用SimpleDateFormat,但它总是返回 1970.01.17 17:48:35 GMT ,而不是实际时间。以下是MVCE:

I have been using Processing 3.0, and I am trying to print a simple timestamp when my Arduino outputs certain values, but it is not working. I tried to use SimpleDateFormat, but it always returns 1970.01.17 17:48:35 GMT, rather than the actual time. Below is the MVCE:

void setup ()
{      
  SimpleDateFormat format = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss z");
  format.setTimeZone (TimeZone.getDefault());

  long timestamp = getTimeNow();
  println(format.format(new Date(timestamp)));
  println(timestamp);
}

long getTimeNow ()
{
   Date d = new Date ();
   Calendar cal = new GregorianCalendar();

   long current = d.getTime()/1000;
   long timezone = cal.get(Calendar.ZONE_OFFSET)/1000;
   long daylight = cal.get(Calendar.DST_OFFSET)/1000;
   return current + timezone + daylight;
}

输出示例:

1970.01.17 17:48:35 GMT 
1442915733

我怀疑问题出在 getTimeNow()上,因为,如果我将值插入在线历元转换器中,则会得到正确的时间。上面的代码有什么问题?

I doubt the issue is with getTimeNow(), since, if I plug the values into an online epoch converter I get the correct time. What is the issue in the above code?

推荐答案

Date 对象参数接受的时间以毫秒为单位,而不是秒。您需要将其乘以1000。并确保提供的时间长。

The Date object parameter accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000. and make sure that you supply it as long.

Date dateObj = new Date(1442915733L * 1000);
System.out.println(dateObj);

这篇关于SimpleDateFormat始终以错误的时区返回1970.01.17的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆