Search code examples
javaspring-bootspring-mvcspring-annotationsdate-conversion

Spring MVC: Convert String Date into Date over REST endpoint


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


Solution

  • 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): enter image description here

    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.