为什么SimpleDateFormat.parse()。getTime()返回一个不正确的(负)值? [英] Why does SimpleDateFormat.parse().getTime() return an incorrect (negative) value?

查看:160
本文介绍了为什么SimpleDateFormat.parse()。getTime()返回一个不正确的(负)值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String类型的时间戳,我试图将它转换为double(并在几秒钟内找到结果),这就是我所做的:

I have a time-stamp of type String and I am trying to convert it to a double (and find the result in seconds) and here is what I have done:

double mytimeStamp = 0;

String timeStamp = new SimpleDateFormat(" mm ss S").format(new Date( ));   

SimpleDateFormat dateFormat = new SimpleDateFormat(" mm ss S");

try {
  mytimeStamp = ((double)dateFormat.parse(timeStamp).getTime())/1000;
} catch (ParseException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
}

System.out.println("timeStamp is: "+ mytimeStamp);

问题是我获得的值如 -2722.515 我不知道为什么。

The problem is that I obtain a value such as -2722.515 and I don't know why.

为什么它是否定的?

有没什么错误的代码?

当我将此时间戳转换为 mm ss S 与真实不符时时间,这似乎是另一个问题!

When I convert this time-stamp to mm ss S does not match with the real time and this seems to be another problem!

推荐答案

这是一个时区差异问题。

It's a time zone discrepancy issue.

由于您只指定了分钟和秒,因此日期将在 1970年1月1日00:mm:ss mm ss 是当前时间的分钟和秒数。

Since you only specified the minute and second, the date will be on 1 Jan 1970 00:mm:ss (mm and ss being the minutes and seconds of the current time).

我简化了你的例如:

String timeStamp = "00 00 00";
SimpleDateFormat dateFormat = new SimpleDateFormat("HH mm ss");
double hour = dateFormat.parse(timeStamp).getTime()/1000.0/60/60;
System.out.println("hour is: "+ hour);

打印出的小时数应为 GMT '偏离当地时区。

The hour printed out should be GMT's offset from the local time zone.

原因是:

SimpleDateFormat 是区分区域敏感的,因此 dateFormat.parse(timeStamp)将返回创建日期给定时区的对象(默认为本地时区)。然后 getTime()获取 1970年1月1日午夜** GMT ** 的毫秒数。因此,该值将被当地时区距 GMT 的距离所抵消。

SimpleDateFormat is locale-sensitive, so dateFormat.parse(timeStamp) will return create a Date object for a given time zone (the default is the local time zone). Then getTime() gets the number of milliseconds from midnight 1 Jan 1970 **GMT**. So the value will be offset by how far the local time zone is from GMT.

如何修复它:

你可以通过设置 dateFormat 对象的时区来修复它code> parse 的调用方式如下:

You could fix it by setting the time zone of the dateFormat object before parse is called as follows:

dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));

这篇关于为什么SimpleDateFormat.parse()。getTime()返回一个不正确的(负)值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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