2016-10-04 89 views
1

我試圖在使用@DateTimeFormat獲取日期爲@PathVariable時使用spring的自動字符串到日期轉換。自動轉換已完成,但出於某種原因,日期轉換爲我通過的日期減去四小時(復活節夏令時,服務器和客戶端均位於此處)。Spring @DateTimeFormat在將@PathVariable轉換爲日期時正在更改時區

實施例:

URL:(即8 PM前一天,這是我的背後通過的日期4小時).../something/04-10-2016/somename會導致具有值2016年10月3日someDate對象20點○○分00秒

如何避免此自動時區轉換。我不需要任何時區信息,並且此轉換正在打破我期望的行爲。

這裏是我的代碼:

@RequestMapping(value = "/something/{someDate}/{name}", method = RequestMethod.GET, headers = "Accept=application/json") 
@ResponseBody 
public SomeObject getDetails(@PathVariable @DateTimeFormat(pattern = "dd-MM-yyyy") Date someDate, 
    @PathVariable String name) { 
    // date here comes as GMT - 4 
    // more code here 
    // return someObject; 
} 

因爲我現在,我身邊這個工作僅僅閱讀路徑變量作爲字符串,並使用SimpleDateFormatter的字符串到日期的手動轉換。

有關如何在沒有時區轉換的情況下獲得自動轉換工作的任何想法?

回答

0

待辦事項新和成VY的answer指出了正確的方向;但不是添加時區信息,而是必須將其刪除。

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

從配置中刪除這一點,並單獨留在家中的默認時區。這對我有效。

+0

嗨Suraj,你可以請分享網址答覆發表於Do Nhu – GSK

0

問題原因可能是時區,java.util.Date即時時間轉換回東部時區,因此您會看到該值。如果你正在使用java8,應該LOCALDATE爲你解決

@PathVariabl @DateTimeFormat(pattern = "dd-MM-yyyy") LocalDate date 

問題整齊下面的帖子一些選項供您

https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-parsing-date-and-time-information-from-a-request-parameter/

+0

我還沒試過這個;但即使它工作,我仍然必須將'LocalDate'轉換爲'Date',因爲我正在使用的API採用Date對象。這幾乎和使用SimpleDateFormatter一樣好。 –

0

我有同樣的問題,我只在我的串行器文件中添加UTC。我的意思是什麼,而不是:

private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.dateHourMinute(); 

我用:

private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.dateHourMinute().withZoneUTC(); 

這是一個完整JsonJodaDateTimeSerializer.java的最終代碼:

package cat.meteo.radiosondatge.commons; 

import com.fasterxml.jackson.core.JsonGenerator; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.JsonSerializer; 
import com.fasterxml.jackson.databind.SerializerProvider; 
import java.io.IOException; 
import org.joda.time.DateTime; 
import org.joda.time.format.DateTimeFormatter; 
import org.joda.time.format.ISODateTimeFormat; 

/** 
* When passing JSON around, it's good to use a standard text representation of 
* the date, rather than the full details of a Joda DateTime object. Therefore, 
* this will serialize the value to the ISO-8601 standard: 
* <pre>yyyy-MM-dd'T'HH:mm:ss.SSSZ</pre> This can then be parsed by a JavaScript 
* library such as moment.js. 
*/ 
public class JsonJodaDateTimeSerializer extends JsonSerializer<DateTime> { 

    private static final DateTimeFormatter FORMATTER = ISODateTimeFormat.dateHourMinute().withZoneUTC(); 

    @Override 
    public void serialize(DateTime value, JsonGenerator gen, SerializerProvider arg2) 
      throws IOException, JsonProcessingException { 

     gen.writeString(FORMATTER.print(value) + 'Z'); 
    } 

} 

此代碼是從Serializing Joda DateTime with Jackson and Spring

提取

希望它有幫助。

相關問題