首页 > 解决方案 > 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 已经是毫秒

标签: javadatetimetimedatetime-formatjava-time

解决方案


您提到的数字 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 帮您自己和维护您的代码的人帮个忙:不要使用旧的、过时的和麻烦的类DateSimpleDateFormat以及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


推荐阅读