java 使用 Spring Rest 服务时在 Date 中获取错误的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44542923/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:14:24  来源:igfitidea点击:

Getting wrong time in Date while using Spring Rest Service

javaspringdatetimeHymansonjava.util.date

提问by Srinu

This is my pojo class

这是我的 pojo 课

public class TeTripCarDtl implements Serializable {

    private static final long serialVersionUID = -7601044160087552575L;

    @Id
    @Column(name = "CAR_ID")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long carId;

    @Column(name = "TRIP_ID")
    private long tripId;

    @Column(name = "VEHICLE_TYPE")
    private String vehicleType;

    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", shape = JsonFormat.Shape.STRING)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "PICKUP_DATE_TIME")
    private Date pickUpDateTime;// Here I am getting wrong time value

    @Temporal(value = TemporalType.TIMESTAMP)
    @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", shape = JsonFormat.Shape.STRING)
    @Column(name = "RETURN_DATE_TIME")
    private Date returnDateTime;// Here I am getting wrong time value

    @Column(name = "PICK_UP_LOCATION")
    private String pickUpLocation;

    @Column(name = "DROP_OFF_LOCATION")
    private String dropOffLocation;

    @Column(name = "CONFIRMED_SPECIAL_EQUIP")
    private String confirmedSpecialEquip;

    @Column(name = "LAST_UPDATED_BY")
    private String lastUpdatedBy;

    @Temporal(TemporalType.DATE)
    @Column(name = "LAST_UPDATED_ON")
    private Date lastUpdatedOn;

    @Temporal(TemporalType.DATE)
    @Column(name = "BOOKING_DATE")
    private Date bookingDate;

    @Column(name = "STATUS")
    private String status;

    public long getCarId() {
        return carId;
    }

    public void setCarId(long carId) {
        this.carId = carId;
    }

    public long getTripId() {
        return tripId;
    }

    public void setTripId(long tripId) {
        this.tripId = tripId;
    }

    public String getVehicleType() {
        return vehicleType;
    }

    public void setVehicleType(String vehicleType) {
        this.vehicleType = vehicleType;
    }

    public Date getPickUpDateTime() {
        return pickUpDateTime;
    }

    public void setPickUpDateTime(Date pickUpDateTime) {
        this.pickUpDateTime = pickUpDateTime;
    }

    public Date getReturnDateTime() {
        return returnDateTime;
    }

    public void setReturnDateTime(Date returnDateTime) {
        this.returnDateTime = returnDateTime;
    }

    public String getPickUpLocation() {
        return pickUpLocation;
    }

    public void setPickUpLocation(String pickUpLocation) {
        this.pickUpLocation = pickUpLocation;
    }

    public String getDropOffLocation() {
        return dropOffLocation;
    }

    public void setDropOffLocation(String dropOffLocation) {
        this.dropOffLocation = dropOffLocation;
    }

    public String getConfirmedSpecialEquip() {
        return confirmedSpecialEquip;
    }

    public void setConfirmedSpecialEquip(String confirmedSpecialEquip) {
        this.confirmedSpecialEquip = confirmedSpecialEquip;
    }

    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(String lastUpdatedBy) {
        this.lastUpdatedBy = lastUpdatedBy;
    }

    public Date getLastUpdatedOn() {
        return lastUpdatedOn;
    }

    public void setLastUpdatedOn(Date lastUpdatedOn) {
        this.lastUpdatedOn = lastUpdatedOn;
    }

    public Date getBookingDate() {
        return bookingDate;
    }

    public void setBookingDate(Date bookingDate) {
        this.bookingDate = bookingDate;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return "TeTripCarDtl [carId=" + carId + ", tripId=" + tripId + ", vehicleType=" + vehicleType
                + ", pickUpDateTime=" + pickUpDateTime + ", returnDateTime=" + returnDateTime + ", pickUpLocation="
                + pickUpLocation + ", dropOffLocation=" + dropOffLocation + ", confirmedSpecialEquip="
                + confirmedSpecialEquip + ", lastUpdatedBy=" + lastUpdatedBy + ", lastUpdatedOn=" + lastUpdatedOn
                + ", bookingDate=" + bookingDate + ", status=" + status + "]";
    }

}

Input json

输入json

    {"vehicleType":"ECAR","pickUpDateTime":"2017-06-10T07:30:04", "returnDateTime":"2017-06-10T07:30:04","pickUpLocation":"PNQ","dropOffLocation":"BOM","confirmedSpecialEquip":"HCL,TCS,INFO","status":"BOOKED"}    

Spring Restcontroller class

Spring Restcontroller 类

@RestController
public class DateControllerTest {

    @RequestMapping(value="date_test", method = RequestMethod.POST)
    public String reciveData(@RequestBody TeTripCarDtl teTripCarDtl){
        System.out.println("PickUpDateAndTime:"+teTripCarDtl.getPickUpDateTime()+","
                + "ReturnDateAndTime:"+teTripCarDtl.getReturnDateTime());
        return "recived";
    }
}

I am printing date values in console it it is printing like this .Here I am getting time is wrong, I suppose to get time 07:30:04but I am getting 13:00:04except this everything is fine

我正在控制台中打印日期值,它是这样打印的。在这里我得到的时间是错误的,我想得到时间07:30:04但我得到13:00:04除了这一切都很好

    PickUpDateAndTime:Sat Jun 10 13:00:04 IST 2017,ReturnDateAndTime:Sat Jun 10 13:00:04 IST 2017

Please help me with this.

请帮我解决一下这个。

采纳答案by Sangam Belose

The @JsonFormat annotations have timeZone issues. Please check the link for more details on issue.Hymanson-data-bind issueOverriding the timezone in ObjectMapper didnt worked either. I have solved the problem by implementing custom Date Deserializer as below:

@JsonFormat 注释有 timeZone 问题。请查看链接以获取有关问题的更多详细信息。Hymanson-data-bind 问题覆盖 ObjectMapper 中的时区也不起作用。我通过实现自定义日期反序列化器解决了这个问题,如下所示:

            @Component
            public class CustomDateDeserializer extends StdDeserializer<Date> {

                /**
                * 
                */
                private static final long serialVersionUID = 1L;
                private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // specify your specific timezone

                public CustomDateDeserializer() {
                this(null);
                }

                public CustomDateDeserializer(Class<?> vc) {
                super(vc);
                }

                @Override
                public Date deserialize(JsonParser jsonparser, DeserializationContext context)
                    throws IOException, JsonProcessingException {
                String date = jsonparser.getText();
                try {
                    return formatter.parse(date);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                }
            }

and then apply the deserializer on setter method of your bean properties.

然后在 bean 属性的 setter 方法上应用反序列化器。

@JsonDeserialize(using = CustomDateDeserializer.class)
public void setReturnDateTime(Date returnDateTime) {
this.returnDateTime = returnDateTime;
}

similarly you can implement your custom serializer for vice versa operation.

同样,您可以实现您的自定义序列化程序,反之亦然。

回答by Daniel Higueras

The Hymanson @JsonFormatannotation has a specific timezoneattribute. If you specify the timezone you wish to use, you can fix this issue.

Hymanson@JsonFormat注释有一个特定的timezone属性。如果您指定要使用的时区,则可以解决此问题。

Example:

例子:

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss", timezone = "Europe/Madrid")

Reference: http://fasterxml.github.io/Hymanson-annotations/javadoc/2.1.0/com/fasterxml/Hymanson/annotation/JsonFormat.html

参考:http: //fasterxml.github.io/Hymanson-annotations/javadoc/2.1.0/com/fasterxml/Hymanson/annotation/JsonFormat.html

回答by talalUcef

I had the same problem before, it's a time zone problem, so I convert my date to string before sending, you can use this function to convert date to string :

我以前遇到过同样的问题,这是一个时区问题,所以我在发送之前将日期转换为字符串,您可以使用此函数将日期转换为字符串:

public static String dateFormatString(Date date, String pattern) {
    if (date != null) {
        SimpleDateFormat formatter = new SimpleDateFormat(pattern);
        return formatter.format(date);
    }
    return null;
}

for the pattern you can use : yyyy-MM-dd HH:mm:ss

对于您可以使用的模式:yyyy-MM-dd HH:mm:ss

回答by Issam EL-ATIF

It is a time zone issue. When you don't specify a timezone Hymanson consider that date is in UTC time and convert it to your default locale which is IST. As you can see 07:30:04 UTCis equivalent to 13:00:04 IST.

这是一个时区问题。当您不指定时区时,Hymanson 考虑该日期是 UTC 时间并将其转换为您的默认语言环境,即 IST。如您所见07:30:04 UTC相当于13:00:04 IST

You can specify timezone in input json like this "pickUpDateTime":"2017-06-10T07:30:04.000+05:30"hence IST=UTC+5:30

您可以像这样在输入 json 中指定时区,"pickUpDateTime":"2017-06-10T07:30:04.000+05:30"因此 IST=UTC+5:30