java - Java时间,无法从纪元秒解析年份
问题描述
我正在尝试解析1523265822618
为时间字符串。但是,它确实适用于除 Year 之外的所有内容。我做错了什么还是Java表现得很奇怪?
long millis = job.lastBuild.timestamp * 1000
Date date = new Date(millis)
SimpleDateFormat sdf = new SimpleDateFormat("EEEE, dd MMMM, yyyy HH:mm:ss", Locale.GERMANY);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = sdf.format(date);
echo """${formattedDate}"""
>>> Samstag, 16 Mai, 50240 11:10:18
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(job.lastBuild.timestamp, 0, ZoneOffset.UTC)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, dd MMMM, yyyy, HH:mm:ss", Locale.GERMANY)
formattedDate = dateTime.format(formatter)
echo """${formattedDate}"""
>>> Samstag, 16 Mai, +50240, 11:10:18
正确的输出是Samstag, 16 Mai, 2018, 11:10:18
抱歉,错误距离屏幕 40 厘米,job.lastBuild.timestamp
感谢 MadProgrammer 已经是毫秒
解决方案
您提到的数字 1523265822618 已经是毫秒。您的错误是由乘以 1000 引起的。不要那样做。
long millis = 1_523_265_822_618L;
System.out.println(Instant.ofEpochMilli(millis));
2018-04-09T09:23:42.618Z
System.out.println(Instant.ofEpochSecond(millis));
+50240-05-16T11:10:18Z
PS 帮您自己和维护您的代码的人帮个忙:不要使用旧的、过时的和麻烦的类Date
,SimpleDateFormat
以及TimeZone
. 坚持使用 java.time,这是您的第二个代码片段中的现代 Java 日期和时间 API。
PPS 对于大多数目的,使用内置格式可以得到更广泛接受的结果,也更容易,例如:
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)
.withLocale(Locale.GERMANY);
System.out.println(Instant.ofEpochMilli(millis)
.atZone(ZoneId.of("Europe/Berlin"))
.format(formatter));
Montag,2018 年 4 月 9 日 um 11:23:42 Mitteleuropäische Sommerzeit
推荐阅读
- heroku - 无法在“完整性”属性中为具有计算的 SHA-256 完整性的资源找到有效的摘要
- javascript - 如何从api获取json数组
- azure-active-directory - 对令牌系统如何与 Auth0 和 Azure AD 一起工作感到困惑
- android - 如何使用命令检查android服务是在后台还是前台运行?
- excel - 范围类的选择方法选择失败
- c++ - 静态数据成员:“const 声明/constexpr 定义”是否有效?
- python - 通过比较两个数据框获取唯一行
- html - 为什么我的元素超出了标题元素
- c++ - C++在函数中泛化二维数组
- perl - Perl - 如何使用 Ping 检查服务器是否处于活动状态?