I want to format a Timestamp field, the value is 2017-08-03 13:30:20 but in my method the hour displayed in the console is wrong? Is it a Jackson format error or does it need a custom serializer?
Java code is as follows:
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());
}
}
console log is
{
"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]
if date is 2017-08-03 7:30:20 console time is 2017-08-02 23:30:20,
if date is 2017-08-03 8:00:00 console time is 2017-08-03 00:00:00,
It's 8 hours too early, is it a timezone or locale problem?