我想格式化一个时间戳字段,值为 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 个小时,是时区问题还是语言环境问题?
最佳答案
问题是因为缺少时区属性。我认为 JSON 使用 UTC 作为时区并应用转换,但这对我有用。
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="IST")
私有(private)时间戳时间;
或者如果你想在全局级别为所有时间戳设置它
ObjectMapper mapper = new ObjectMapper();
mapper.setTimeZone(TimeZone.getTimeZone("IST"));
顺便说一句,这也适用于我。
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(sdf);
关于java - 为什么用 Jackson 的 @JsonFormat 注释的 java.sql.Timestamp 字段中的小时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45476329/