将日期时间格式从Web服务转换为字符串 [英] Convert datetime format from web service to a string

查看:178
本文介绍了将日期时间格式从Web服务转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的POM.xml ..错误是覆盖管理版本2.8.2 for joda-time

This is my POM.xml .. Error is Overriding managed version 2.8.2 for joda-time

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0   http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>gs-rest-service-cors</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>


<dependencies>

<dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-joda</artifactId>
        <version>2.4.3</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>


    <dependency>
        <groupId>joda-time</groupId>
        <artifactId>joda-time</artifactId>
        <version>2.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>


</dependencies>


<properties>
    <java.version>1.8</java.version>
</properties>


<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-releases</id>
        <url>https://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>

我的json数据Web服务

My json data on web service

 [{"id":2,"cameraid":"004","timestamp":{"centuryOfEra":20,"yearOfEra":2016,"yearOfCentury":16,"weekyear":2016,"monthOfYear":11,"weekOfWeekyear":48,"dayOfMonth":29,"dayOfWeek":2,"era":1,"dayOfYear":334,"year":2016,"millisOfSecond":0,"millisOfDay":5521000,"secondOfMinute":1,"secondOfDay":5521,"minuteOfHour":32,"minuteOfDay":92,"hourOfDay":1,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"},"millis":1480354321000,"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"}},"afterNow":true,"beforeNow":false,"equalNow":false},"filename":"ogh.png"}
,{"id":3,"cameraid":"002","timestamp":{"centuryOfEra":20,"yearOfEra":2015,"yearOfCentury":15,"weekyear":2015,"monthOfYear":6,"weekOfWeekyear":25,"dayOfMonth":15,"dayOfWeek":1,"era":1,"dayOfYear":166,"year":2015,"millisOfSecond":982,"millisOfDay":81921982,"secondOfMinute":21,"secondOfDay":81921,"minuteOfHour":45,"minuteOfDay":1365,"hourOfDay":22,"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"},"millis":1434379521982,"chronology":{"zone":{"uncachedZone":{"cachable":true,"fixed":false,"id":"Asia/Kuala_Lumpur"},"fixed":false,"id":"Asia/Kuala_Lumpur"}},"afterNow":false,"beforeNow":true,"equalNow":false},"filename":"ydd.png"},

我的模型类:

public class Record {

@Id private Long id;
private String cameraid;
private DateTime timestamp;
private String filename;


public Record(Long id,String cameraid, DateTime timestamp, String filename) {
    this.id = id;
    this.cameraid = cameraid;
    this.timestamp = timestamp;
    this.filename = filename;
}

我的控制器类:

@Autowired
RecordRepository rep;

@RequestMapping(value="list")
public List<Record> getList() {
List<Record> recordList = rep.findAll(); 
return recordList;

MongoRepository类:

MongoRepository class:

import org.springframework.data.mongodb.repository.MongoRepository;

public interface RecordRepository extends MongoRepository<Record, String> {

}

如何以这种格式显示时间戳(2016- 07-16T19:20:30 + 01:00)?

How to display the timestamp as this format (2016-07-16T19:20:30+01:00) on the web service?

推荐答案

有两种方法可以实现。


  1. 使用杰克逊序列化器 - 用于全局转换。适用于每次转换

  2. 用户Spring WebDataBinder和PropertyEditorSupport。您可以选择哪个控制器需要进行此转换

实施Jackson序列化器

注册上面的杰克逊模块

public class CustomDateTimeSerializer extends JsonSerializer<DateTime> {
    // Customize format as per your need 
    private static DateTimeFormatter formatter = DateTimeFormat
            .forPattern("yyyy-MM-dd'T'HH:mm:ss");

    @Override
    public void serialize(DateTime value, JsonGenerator generator,
                          SerializerProvider serializerProvider)
            throws IOException {
        generator.writeString(formatter.print(value));
    }

}

将Serializer添加到Jackson Module



Add Serializer to Jackson Module

@Configuration
public class JacksonConfiguration {

    @Bean
    public JodaModule jacksonJodaModule() {
        final JodaModule module = new JodaModule();
        module.addSerializer(DateTime.class, new CustomDateTimeSerializer());
        return module;
    }
}

使用WebBinder API和PropertyEditorSupport

实现PropertyEditorSupport

Implement PropertyEditorSupport

public class DateTimeEditor extends PropertyEditorSupport {

    private final DateTimeFormatter formatter;

    public DateTimeEditor(String dateFormat) {
        this.formatter = DateTimeFormat.forPattern(dateFormat);
    }

    public String getAsText() {
        DateTime value = (DateTime) getValue();
        return value != null ? value.toString(formatter) : "";
    }

    public void setAsText( String text ) throws IllegalArgumentException {
        if ( !StringUtils.hasText(text) ) {
            // Treat empty String as null value.
            setValue(null);
        } else {
            setValue(new DateTime(formatter.parseDateTime(text)));
        }
    }
}

将此PropertyEditor添加到Rest Controller

Add this PropertyEditor to Rest Controller

@RestController
@RequestMapping("/abc")
public class AbcController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(DateTime.class, new DateTimeEditor("yyyy-MM-dd", false));
    }

}

这篇关于将日期时间格式从Web服务转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆