如何将 getTime() 转换为 'YYYY-MM-DD HH24:MI:SS'



我在应用程序中具有以下代码

System.out.println(rec.getDateTrami().getTime());

我需要转换以下格式(我想它们是秒)

43782000
29382000
29382000

为格式 YYYY-MM-DD HH24:MI:SS,任何人都可以帮助我吗?

您可以使用SimpleDateFormat

示例:

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = new Date();
date.setTime(rec.getDateTrami().getTime());
System.out.println(format.format(date));

文档:简单的Format,dateformat

使用java.time

最好如果您可以更改getDateTrami()以从java.time返回OffsetDateTimeZonedDateTimejava.time是现代Java日期和时间API。它也称为JSR-310。不管返回两种类型中的哪一种:

,代码都是相同的
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    System.out.println(rec.getDateTrami().format(formatter));

这将打印一个日期和时间

2017-12-14 16:52:20

java.time通常比过时的Date级及其朋友更好地使用。

如果您无法更改返回类型

我假设getDateTrami()返回java.util.Date。由于Date类长期过时,因此要做的第一件事是将其转换为java.time.Instant。从那里您进行进一步的操作:

    Date oldfashionedDateObject = rec.getDateTrami();
    ZonedDateTime dateTime = oldfashionedDateObject.toInstant()
            .atZone(ZoneId.of("Atlantic/Cape_Verde"));
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    System.out.println(dateTime.format(formatter));

当然,结果与上述相似。我是故意的,在我想解释时间点的时区。如果不是碰巧是大西洋/cape_verde。

,请替换自己

格式化秒以来,

    int seconds = 29_382_000;
    ZonedDateTime dateTime = Instant.ofEpochSecond(seconds)
            .atZone(ZoneId.of("Atlantic/Cape_Verde"));
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    System.out.println(dateTime.format(formatter));

此摘要打印

1970-12-06 23:40:00

1970年12月的日期。如果这是不正确的,那是因为自1970年1月1日午夜在UTC的时代以来,29 382 000并未表示秒数,也称为Unix时代。这是迄今为止最常见的时间来衡量秒的时间。如果您的秒是从其他一些固定点测量的,我无法猜测哪个,您还有一份工作要做。再次确定您要指定的时区。

您可以使用SimpleDateFormat。

new SimpleDateFormat("YYYY-MM-DD HH24:MI:SS").format(date)

相关内容

最新更新