Spring MVC:通过REST端点将字符串日期转换为日期

huangapple go评论65阅读模式
英文:

Spring MVC: Convert String Date into Date over REST endpoint

问题

我正在开发Spring Boot项目,并且想要将来自POST请求的字符串日期转换为java.time对象。

要转换的日期在粗体部分,需要从@PostMapping方法的请求参数中提取并转换。

在搜索后,我找到了一些关于如何处理数据本身的解决方案,但没有使用Spring,但对我不起作用,使用了java.util.Date。以下是我迄今为止编写的代码:

    class Main {
      public static void main(String[] args) throws ParseException {
        String date = "2020-08-05 20:18:33.32692";
        System.out.println(convertDate(date)); //Wed Aug 05 20:19:05 UTC 2020
      }
    
       public static Date convertDate(String date) throws ParseException {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS");
            return formatter.parse(date);
        }
    }

但我得到的响应不是我期望的结果,有没有办法解决这个问题?

英文:

I'm working on Spring boot project and I want to convert a String date coming from a post request

> D,100000001028686,BA0884,72087000000176,N,2,147568593,DEPOSITREFERENCE,2020-08-05
> 20:17:33.32691
,
> 601123,ZAR,2500,57,24,i10c=0,i20c=2,i50c=5,iR1=2,iR2=5,iR5=8,iR10=200,iR20=1,iR50=55,iR100=60,iR200=82,0,0,0,0,000

The date that I want to convert is in Bold and need to convert that part from a @PostMapping method request parameter into one of the java.time Objects.

After searching I found some solution for the data if self without using Spring but it did not work for me and used java.util.Date, here the code I wrote so far

    class Main {
      public static void main(String[] args) throws ParseException {
        String date = "2020-08-05 20:18:33.32692";
        System.out.println(covertDate(date)); //Wed Aug 05 20:19:05 UTC 2020
      }
    
       public static Date covertDate(String date) throws ParseException {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSS");
            return formatter.parse(date);
        }
    }

The response I got is not what I'm looking for, is there any way to solve the problem

答案1

得分: 2

以下是翻译好的部分:

这里是我在寻找未来解决方案后找到的解决方案。
我使用了Java 8 API来解决它。

 class Main {
  public static void main(String[] args) throws ParseException {
    String sDate6 = "2020-08-05 11:50:55.555";
    System.out.println(covertDate(sDate6)); //2020-08-05T11:50:55.555
  }

   public static LocalDateTime covertDate(String date) throws ParseException {
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
         LocalDateTime dateTime = LocalDateTime.parse(date,formatter);
         return dateTime;  
    }
}

请注意,我已将HTML实体编码(例如")还原为正常的文本。

英文:

Here the solution I found after searching for future
I used Java 8 API to solve it

 class Main {
  public static void main(String[] args) throws ParseException {
    String sDate6 = "2020-08-05 11:50:55.555";
    System.out.println(covertDate(sDate6)); //2020-08-05T11:50:55.555
  }

   public static LocalDateTime covertDate(String date) throws ParseException {
         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
         LocalDateTime dateTime = LocalDateTime.parse(date,formatter);
         return dateTime;  
    }
}

答案2

得分: 1

JShell(Java版本14)中,我运行了您的代码,并且能够获得类似的结果(尽管它是在GMT而不是UTC;但是,秒数的偏移量与您当前的输出相同):

如果问题涉及UTC:

我建议使用Instant,因为它避免了LocalDateTime多年来提出的许多问题。正如在评论中提到的那样,通常最好避免使用java.util.Date,而改用Instant(或者您也可以使用更传统的LocalDateTime)。

如果您正在谈论Spring的带注解的@PostMapping方法以自动解析日期,您可以使用类似以下的内容:

@PostMapping
public String postDate(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Long dateReq) {
  Instant date = Instant.ofEpochMilli(dateReq);
  System.out.println(date);
}

如果您想要使用自定义格式化程序,则可以在postDate方法的参数中使用@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSSS") LocalDateTime date

请注意,Spring的文档规定@DateTimeFormat的模式字段使用与java.text.SimpleDateFormat相同的模式。因此,这可能会有用。

英文:

In JShell (Java Version 14) I ran your code and was able to get the similar results (Granted it is in GMT and not UTC; however, the seconds are offset by the same amount as your current output):
Spring MVC:通过REST端点将字符串日期转换为日期

If the question is about UTC:

I would suggest to use Instant as it avoids many of the issues that LocalDateTime has presented over the years. As mentioned in the comments is it generally best to avoid using java.util.Date and to use Instant instead (or you could use the more traditional LocalDateTime).

If you are talking about Spring's annotated @PostMapping method to parse out the date automatically you could use something like:

@PostMapping
public String postDate(@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Long dateReq) {
  Instant date = Instant.ofEpochMilli(dateReq);
  System.out.println(date);
}

If you wanted to use your custom formatter the you could do @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSSS" LocalDateTime date) as the parameter of the postDate method.

Please note that Spring's docs state that the pattern field of @DateTimeFormat uses the same patterns as java.text.SimpleDateFormat. So that could be of use.

huangapple
  • 本文由 发表于 2020年8月7日 02:17:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63289518.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定