有人可以找到此代码的错误。我试图使用日期和时间戳将日期时间值转换为长。这两个总是在相同的日期时间返回两个不同的值。
String date = "2016-01-08 06:23:13.0";
if(date.lastIndexOf('.') != -1)
{
date = date.substring(0,date.lastIndexOf('.'));
date = date+"+0000";
}
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
Date myDate = fmt.parse(date);
System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println("The time stamp value is " + timestamp);
Timestamp tm = Timestamp.valueOf("2016-01-08 06:23:13.0");
System.out.println("The time stamp value using Timestamp is " + tm.getTime());
答案 0 :(得分:0)
您正在为第一个变体添加时区规范:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
^
如果省略此项,并为两次计算指定相同的输入值,结果都是相同的。
...
String date = "2016-01-08 06:23:13";
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate = fmt.parse(date);
System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println("The time stamp value is " + timestamp);
Timestamp tm = Timestamp.valueOf(date);
long t2 = tm.getTime();
System.out.println("The time stamp value using Timestamp is " + t2 + " (diff: " + (t2 - timestamp) + ")");
...
Fri Jan 08 06:23:13 CET 2016
The time stamp value is 1452230593000
The time stamp value using Timestamp is 1452230593000 (diff: 0)
请参阅@ Joni的答案进行解释:
+0000
,您可以指定UTC + 0作为时区答案 1 :(得分:0)
使用SimpleDateFormat的代码解析日期,假设零位指定UTC时区。时间戳采用当地时区。