我想格式化Timestamp字段,值为2017-08-03 13:30:20
但是在我的方法中,控制台中显示的小时是错误的?它是Jackson格式错误还是需要自定义序列化程序?
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 :(得分: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);