我一直在使用Processing 3.0,当我的Arduino输出某些值时,我正在尝试打印一个简单的时间戳,但它无效.我尝试使用SimpleDateFormat,但它总是返回1970.01.17 17:48:35 GMT,而不是实际时间.以下是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;
}
Run Code Online (Sandbox Code Playgroud)
输出示例:
1970.01.17 17:48:35 GMT
1442915733
Run Code Online (Sandbox Code Playgroud)
我怀疑问题是什么getTimeNow(),因为,如果我将值插入在线纪元转换器,我得到正确的时间.上面的代码有什么问题?
我正在尝试将 19 位 Unix 时间戳(例如(五分之一))转换为1558439504711000000可读的日期/时间格式。我的时间戳以 6 个零结尾,这表明时间以纳秒为单位。
我遇到过一些例子,人们使用了我不需要的时区。另一个例子使用 ofEpochSecond ,如下所示:
Instant instant = Instant.ofEpochSecond(seconds, nanos);
Run Code Online (Sandbox Code Playgroud)
但我不确定是否需要使用ofEpochSecond。
下面的代码给出了我实现这一目标的最新方法:
String timeStamp = "1558439504711000000";
long unixNanoSeconds = Long.parseLong(timeStamp);
Date date = new java.util.Date(timeStamp*1000L);
// My preferred date format
SimpleDateFormat sdf = new java.text.SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String formattedDate = sdf.format(date);
System.out.println("The timestamp in your preferred format is: " + formattedDate);
Run Code Online (Sandbox Code Playgroud)
但我得到的输出是这样的:
// The timestamp in your preferred format is: 11-12-49386951 11:43:20
Run Code Online (Sandbox Code Playgroud)
其中不显示年份格式,例如 2019 格式。