发布日期被序列化为错误的日期,并有1天休息时间

问题描述 投票:1回答:3

enter image description here

我将数据departureTime: "2019-10-21"发布到我的端点,并在spring程序中输出接收到的离开时间变量。

@CrossOrigin(origins = "*")
@RequestMapping(value="/travel/query", method= RequestMethod.POST)
public ArrayList<TripResponse> query(@RequestBody QueryInfo info,@RequestHeader HttpHeaders headers){

    if(info.getStartingPlace() == null || info.getStartingPlace().length() == 0 ||
            info.getEndPlace() == null || info.getEndPlace().length() == 0 ||
            info.getDepartureTime() == null){
        System.out.println("[Travel Service][Travel Query] Fail.Something null.");
        ArrayList<TripResponse> errorList = new ArrayList<>();
        return errorList;
    }
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    Calendar ca = Calendar.getInstance();
    ca.setTime(info.getDepartureTime());
    System.out.println("Departure date is " + format.format(ca.getTime()));

    ...
}

控制台显示“出发日期为2019-10-20”。

运行我的spring程序的服务器应该在UTC-7时区。

知道为什么会发生此错误?如何进行最小的更改来解决它?

java spring microservices
3个回答
1
投票

[避免使用SimpleDateFormatCalendar,而是使用ZonedDateTime

示例:

ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))

样本输出:

2019-10-22

或者可能是您的系统日期和时间设置错误。


0
投票

Calendar.getInstance()将根据服务器所在的位置设置时区。因此,如果您不在UTC-7时区,则会发现时间差异。

最好的解决方法通常是使用特定时区(例如UTC或用于数据的任何其他时区)。然后,您可以为该特定时区获取Calendar,如下所示:

Calendar.getInstance(TimeZone.getTimeZone("UTC"))

0
投票

另一种解决方案(虽然不是聪明的解决方案,但是可行),可以在dateField中将DTOs定义为String字段。因此,您发送的内容将相同,不会基于时区或其他内容进行日期转换。然后,您可以将该字符串转换为您的优惠日期format/timezone

© www.soinside.com 2019 - 2024. All rights reserved.