scala 日期时间格式设置为尾随零,并捕捉到毫米、微米或纳米格式

ehxuflar  于 2023-10-18  发布在  Scala
关注(0)|答案(1)|浏览(101)

我有一些这样的代码

import java.time.Instant

val tstamp = 1546344620.1877
val nanoAdj = ((BigDecimal(tstamp) - tstamp.toLong) * 1000000000).toLong
Instant.ofEpochSecond(tstamp.toLong, nanoAdj).toString
// will print : 2019-01-01T12:10:20.187700Z

ofEpochSecond创建的Instant对象中的toString很棒,可以将尾随的零设置为milli/micro/nano组,但我很难让格式化后的对象也这样做。我需要将格式稍微更改为类似2019-01-01 12:10:20.187700 UTC的格式
其他例子:

2019-01-01 12:10:20 UTC // no fractions
2019-01-01 12:10:20.180 UTC // milliseconds
2019-01-01 12:10:20.187700 UTC // microseconds
2019-01-01 12:10:20.187738200 UTC // nanoseconds

我使用DateTimeFormatter如下,但我对其他建议持开放态度。

def formatter: DateTimeFormatter = {
      val tz_format = new DateTimeFormatterBuilder()
        .optionalStart
        .parseCaseSensitive()
        .appendZoneRegionId()
        .toFormatter

      val datetime_format = new DateTimeFormatterBuilder()
        .appendValue(HOUR_OF_DAY, 2)
        .appendLiteral(':')
        .appendValue(MINUTE_OF_HOUR, 2)
        .optionalStart()
        .appendLiteral(':')
        .appendValue(SECOND_OF_MINUTE, 2)
        .optionalStart()
        .appendFraction(NANO_OF_SECOND, 0, 9, true)
        .toFormatter

      new DateTimeFormatterBuilder()
        .parseCaseInsensitive
        .append(ISO_LOCAL_DATE)
        .appendLiteral(' ')
        .append(datetime_format)
        .appendLiteral(' ')
        .append(tz_format)
        .toFormatter
        .withZone(ZoneId.of("UTC"))
    }
2vuwiymt

2vuwiymt1#

正如Andreas在评论中所说,格式化类DateTimeFormatter不支持这个漂亮的功能。我最好的建议是利用LocalTime.toString(),它有它。在Java语法中(对不起,我没有Scala开发环境):

private static final DateTimeFormatter dateFormatter
        = DateTimeFormatter.ofPattern("uuuu-MM-dd ");

private static String formatEpochSeconds(String epochSeconds) {
    BigDecimal totalSeconds = new BigDecimal(epochSeconds);
    long seconds = totalSeconds.longValue();
    long nanos = totalSeconds.subtract(new BigDecimal(seconds))
            .multiply(new BigDecimal(TimeUnit.SECONDS.toNanos(1)))
            .longValue();
    OffsetDateTime dateTime = Instant.ofEpochSecond(seconds, nanos)
            .atOffset(ZoneOffset.UTC);
    return dateTime.format(dateFormatter)
            + dateTime.toLocalTime()
            + " UTC";
}

试试看:

System.out.println(formatEpochSeconds("1546344600.0"));
    System.out.println(formatEpochSeconds("1546344620.0"));
    System.out.println(formatEpochSeconds("1546344620.18"));
    System.out.println(formatEpochSeconds("1546344620.1877"));
    System.out.println(formatEpochSeconds("1546344620.1877382"));

输出为:

2019-01-01 12:10 UTC
2019-01-01 12:10:20 UTC
2019-01-01 12:10:20.180 UTC
2019-01-01 12:10:20.187700 UTC
2019-01-01 12:10:20.187738200 UTC

如果秒为0.0,则完全忽略秒。如果你不想这样做,你需要编写一个特殊的案例。

相关问题