30秒似乎是1小时30秒?

la_*_*_it 2 java time apache-flink

我想验证我的时间戳.我附上了代码片段:

import org.apache.flink.streaming.api.windowing.time.Time;   

Date date = new Date(Time.seconds(30).toMilliseconds());
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
String dateFormatted = formatter.format(date);
logger.debug(Time.seconds(30).toMilliseconds() + " " + dateFormatted);
Run Code Online (Sandbox Code Playgroud)

事实证明,结果是:

30000 01:00:30:000
Run Code Online (Sandbox Code Playgroud)

编辑:

   [user@hdp ~]$ date
   Thu Jun 29 11:39:27 CEST 2017
Run Code Online (Sandbox Code Playgroud)

我错过了什么?谢谢!

Jes*_*per 7

我不知道Time你的代码中有什么,但我认为Time.seconds(30).toMilliseconds()它将返回30,000(30秒内的毫秒数).

您正在以java.util.Date不是为其设计的方式使用类.Class Date实际上是一个时间戳,它包含自固定参考点(01-01-1970,00:00:00 GMT)以来的毫秒数.

在以下代码行中,您使用类Date来存储一个时间(小时,分钟,秒和毫秒):

Date date = new Date(Time.seconds(30).toMilliseconds());
Run Code Online (Sandbox Code Playgroud)

Class Date不是为此设计的,不适合只存储一次.上面的行中发生的是你得到一个Date对象,该对象指的是格林尼治标准时间01-01-1970 00:00:30(格林威治标准时间1970年1月1日午夜后30秒).

然后使用a将其格式化为字符串SimpleDateFormat.您自己的时区很可能比GMT提前1小时,SimpleDateFormat并将使用您当地的时区来格式化日期.

如果您需要存储一天中的某个时间(小时,分钟,秒和毫秒),则使用class java.time.LocalTime而不是class java.util.Date.如果您需要存储持续时间,请使用类java.time.Duration:

Duration d = Duration.ofSeconds(30);
Run Code Online (Sandbox Code Playgroud)

您应该使用新java.timeAPI而不是旧java.util.Date类,因为它更好.如果您使用的是较旧的Java版本(早于Java 8),那么Joda Time是一个不错的选择.