我如何将时间从毫秒转换为日期?

How can i convert time from milis to date with time?

我有一个 class:

public class Test{
   private String name;
   private ZonedDateTime date1;
   private ZonedDateTime date2;

而且我还有一个方法来表示 JSON 格式的对象:

private String convertTestToJson(Test test) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.registerModule(new JavaTimeModule());
            return mapper.writeValueAsString(test);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

当我创建对象时,我尝试在控制台中输出结果,我得到了正确的 json 格式和正确的字段,但时间以毫秒表示:

{"reportType":"Test name","date1":1615978661.832223700,"date2":1615978661.837225400}

但我想以正常格式获取日期,例如年-月-日时-分-秒-毫,但是当我删除此行时:mapper.registerModule(new JavaTimeModule()); 我得到了异常:

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.ZonedDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:77)
    at com.fasterxml.jackson.databind.SerializerProvider.reportBadDefinition(SerializerProvider.java:1276)
    at com.fasterxml.jackson.databind.ser.impl.UnsupportedTypeSerializer.serialize(UnsupportedTypeSerializer.java:35)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:770)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
    at com.fasterxml.jackson.databind.ObjectMapper._writeValueAndClose(ObjectMapper.java:4487)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3742)
    at com.mycroft.report.Report.convertReportToJson(Test.java:38)
    at com.mycroft.report.Report.generateReport(Test.java:30)
    at com.mycroft.Main.main(Main.java:21)

我也有依赖了:

        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>2.12.2</version>
        </dependency>

问题是我如何以正确的格式表示日期,而不是以毫秒为单位?

按如下方式更改您的 class:

public class Test{
   private String name;

   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
   private ZonedDateTime date1;

   @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
   private ZonedDateTime date2;

这应该可以解决您的问题。
资料来源: