将时间戳转换为ISO格式的日期字符串



我有一个python逻辑,我正在转换为Java代码。逻辑是我需要从JSON文件中的时间戳属性读取并将其转换为ISO日期格式。Python查询:

datetime.datetime.fromtimestamp(jsonMsg["time"]).isoformat(timespec='seconds')
下面是我用Java写的代码1627065646.444是我从JSON脚本 得到的值的一个例子
long timestamp = (long) 1627065646.444 * 1000;
Timestamp time = new Timestamp(timestamp);
Date d = new Date(time.getTime());
DateFormat df = new SimpleDateFormat();
String dateToString = df.format(d);

LocalDateTime datetime = LocalDateTime.parse(dateToString, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
ZoneOffset offset = ZoneOffset.UTC;
String formattedTimeStamp = datetime.atOffset(offset).toString();

当我运行代码时,我得到编译错误"文本'7/23/21 11:40 AM'无法在索引0处解析在java.time.format.DateTimeFormatter.parseResolved0"此异常发生在LocalDateTime。解析(dateToString DateTimeFormatter.ISO_LOCAL_DATE_TIME。有没有人能帮助我理解我在这里做错了什么。

java.time

java.utilDate-Time API及其格式化APISimpleDateFormat过时且容易出错。建议完全停止使用它们,切换到现代的Date-Time API*

使用java.time的解决方案,现代日期-时间API:

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
long timestamp = (long) (1627065646.444 * 1000);
Instant instant = Instant.ofEpochMilli(timestamp);
System.out.println(instant);
ZonedDateTime zdt = instant.atZone(ZoneOffset.UTC);
LocalDateTime ldt = zdt.toLocalDateTime();
System.out.println(ldt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:m:s a", Locale.ENGLISH);
String formatted = dtf.format(zdt);
System.out.println(formatted);
}
}

输出:

2021-07-23T18:40:46.444Z
2021-07-23T18:40:46.444
7/23/2021 6:40:46 PM
<<p>

在线演示/kbd>输出中的Z是零时区偏移的时区指示符。它代表Zulu,并指定Etc/UTC时区(其时区偏移量为+00:00小时)。

了解更多关于现代日期时间API*Trail: Date Time.

除此之外,你的代码还有什么问题?

你已经做了

long timestamp = (long) 1627065646.444 * 1000;

,其中1627065646.444将被强制转换为long,从而得到1627065646,因此乘法的结果将是1627065646000,而不是您期望的1627065646444。您需要在执行乘法运算后转换为long

Ole v.v.的宝贵评论:

我会使用Math.round(1627065646.444 * 1000)来确保这一点处理浮点不精确


*无论什么原因,如果你必须坚持Java 6或Java 7,你可以使用ThreeTen-Backport支持大部分java。time功能到Java 6 &7. 如果你正在为一个Android项目工作,而你的Android API级别仍然不符合Java-8,请检查Java 8+ API,通过desugaring和如何在Android项目中使用ThreeTenABP。

最新更新