Sér*_*els 5 java spring-mvc jodatime dst
我在配置了夏令时的机器上使用Spring MVC(America/Sao_Paulo Time Zone).在我的表单类中,我使用注释DateTimeFormat来配置我的Date的输出:
public class JustificativaOcorForm {
...
@NotNull
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date dataMarcacao;
...
}
Run Code Online (Sandbox Code Playgroud)
在调试时我得到的日期是16/10/2011(日/月/日),这是白天时间的开始,但是Spring将它转换为2011-10-15.为什么?
2011-11-04 16:35:31,965 [http-8080-Processor25] DEBUG org.springframework.core.convert.support.GenericConversionService - Converting value Sun Oct 16 00:00:00 BRST 2011 of [TypeDescriptor @javax.validation.constraints.NotNull @org.springframework.format.annotation.DateTimeFormat java.util.Date] to [TypeDescriptor java.lang.Long]
2011-11-04 16:35:31,965 [http-8080-Processor25] DEBUG org.springframework.core.convert.support.GenericConversionService - Converted to 1318730400000
2011-11-04 16:35:32,010 [http-8080-Processor25] DEBUG org.springframework.core.convert.support.GenericConversionService - Converted to '2011-10-15'
Run Code Online (Sandbox Code Playgroud)
我看到了这个问题:Spring中的@DateTimeFormat产生了一天一天的错误
但是Spring 3使用了Joda-Time,我的classpath中有joda-time-2.0.jar所以我不知道为什么会这样,以及我如何解决它.
[编辑]
我已经测试了创建LocalData对象,并找到了一些东西:
LocalDate ld = new LocalDate( new SimpleDateFormat("dd/MM/yyyy").parse("16/10/2011").getTime() );
System.out.println( new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z z").format( ld.toDate() ) );
//prints 15/10/2011 00:00:00 -0200 BRST
LocalDate ld2 = new LocalDate( 2011,10,16 );
System.out.println( new SimpleDateFormat("dd/MM/yyyy HH:mm:ss Z z").format( ld2.toDate() ) );
//prints 16/10/2011 00:00:00 -0200 BRST
Run Code Online (Sandbox Code Playgroud)
似乎第一种方法是认为时间是UTC,因为调试我可以看到Joda使用类DateTimeZone的convertUTCToLocal方法.
也许这也是Spring的默认值,他预计UTC也会有一个日期,而我正在通过BRT日期.
所以我认为我的解决方案是将对象更改为LocalDate,并使用第二种方法创建此对象的实例.
这可能会回答您问题的部分内容.
什么时候有一个java.util.Data对象,它将在你的系统时区内打印到toString中.因此,如果您将日期设置为UTC 2011-10-16 00:00:00,该日期将在日期内部转换为UTC时间戳.toString将在您当地时区打印该时间戳,这将是UTC 之后的几个小时(因为圣保罗位于伦敦西部)所以大致在2011-10-15 22:00:00.这就是你在断点和调试打印上看到的.尽管如此,数据内部可能仍然是正确的.
如果发现打印日期的唯一真正方式是通过SimpleDateFormat这样:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date dateInUTC = dateFormat.parse("2011-10-16 00:00:00");
Date currentDate = new Date();
String stringInUTC = dateFormat.format(currentDate);
System.out.println(dateInUTC);
System.out.println(currentDate);
System.out.println(stringInUTC);
}
catch (ParseException e) {
// not too worry, I wrote a nice date
}
Run Code Online (Sandbox Code Playgroud)
现在打印件看起来很混乱
Sun Oct 16 01:00:00 CET 2011
Thu Nov 10 15:47:46 CET 2011
2011-11-10 14:47:46
Run Code Online (Sandbox Code Playgroud)
但是让我们来看看吧.
那就是说,java和日期会混淆你,直到你拔掉头发:)
希望这会有所帮助.