2017-08-03 166 views
2

我想格式化时间戳字段,值为2017-08-03 13:30:20,但在我的方法中控制台中显示的小时数是错误的?这是一个杰克逊格式错误还是需要一个自定义序列化程序?为什么在用Jackson的@JsonFormat注释的java.sql.Timestamp字段中错误的时间?

Java代码如下:

package demo.bean; 

import com.fasterxml.jackson.annotation.JsonFormat; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.databind.ObjectMapper; 

import java.sql.Timestamp; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 


public class TimestampDemo { 
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") 
    private Timestamp time; 

    public Timestamp getTime() { 
     return time; 
    } 

    public void setTime(Timestamp time) { 
     this.time = time; 
    } 

    public static void main(String[] args) { 
     SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
     Date date = null; 
     try { 
      date = sdf.parse("2017-08-03 13:30:20"); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     TimestampDemo demo = new TimestampDemo(); 
     demo.setTime(new Timestamp(date.getTime())); 
     ObjectMapper mapper = new ObjectMapper(); 
     try { 
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString((demo))); 

     } catch (JsonProcessingException e) { 
      e.printStackTrace(); 
     } 
     System.out.println(Locale.getDefault()); 
     System.out.println(TimeZone.getDefault()); 
    } 
} 

控制台日志

{ 
    "time" : "2017-08-03 05:30:20" 
} 
zh_CN 
sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null] 

如果日期是2017-08-03 7:30:20控制台时间2017-08-02 23:30:20

如果日期是2017-08-03 8:00:00控制台时间2017-08-03 00:00:00

8小时太早了,是时区还是区域设置问题?

+0

我的配置是'mapper.setTimeZone(TimeZone.getTimeZone( “亚洲/上海”));' –

回答

1

问题是因为缺少时区属性。我认为JSON使用UTC作为时区并应用转换,但这对我有用。

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss" ,timezone="IST") private Timestamp time;

或者如果你想在全球层面设定所有时间戳

ObjectMapper mapper = new ObjectMapper(); mapper.setTimeZone(TimeZone.getTimeZone("IST"));

顺便说一句,这也为我工作。

ObjectMapper mapper = new ObjectMapper(); mapper.setDateFormat(sdf);

相关问题