在我的 Grails 应用程序中,从数据库读取的原始日期等于:
{ endDate=2015-10-19 19:00:00.0}
{"endDate": "2015-10-19T16:00:00Z"}
最佳答案
根据您所在的时区,2015-10-19 19:00:00.0
和 2015-10-19T16:00:00Z
可能不是不同的时间,它们可能只是同一时间(瞬间)的不同表示。
就我而言,我使用自定义编码器来确保我的 API 的 JSON 响应中的时间始终使用 UTC 时区。我的自定义编码器如下所示:
import org.springframework.stereotype.Component
@Component
class DateMarshaller implements CustomMarshaller {
@Override
def getSupportedTypes() {
Date
}
@Override
Closure getMarshaller() {
{ Date date ->
TimeZone tz = TimeZone.getTimeZone('UTC')
date?.format("yyyy-MM-dd'T'HH:mm:ss'Z'", tz)
}
}
}
Config.groovy
中注册此编码器用于 Spring bean 扫描的包.它实现的接口(interface)是:interface CustomMarshaller {
/**
* Indicates the type(s) of object that this marshaller supports
* @return a {@link Class} or collection of {@link Class}
* if the marshaller supports multiple types
*/
def getSupportedTypes()
Closure getMarshaller()
}
CustomMarshaller
实例。对于相关类型:import grails.converters.JSON
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import javax.annotation.PostConstruct
class MarshallerRegistrarService implements ApplicationContextAware {
static transactional = false
ApplicationContext applicationContext
// a combination of eager bean initialization and @PostConstruct ensures that the marshallers are registered when
// the app (or a test thereof) starts
boolean lazyInit = false
@PostConstruct
void registerMarshallers() {
Map<String, CustomMarshaller> marshallerBeans = applicationContext.getBeansOfType(CustomMarshaller)
marshallerBeans.values().each { CustomMarshaller customMarshaller ->
customMarshaller.supportedTypes.each { Class supportedType ->
JSON.registerObjectMarshaller supportedType, customMarshaller.marshaller
}
}
}
}
https://stackoverflow.com/questions/37533228/