'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 1:[1]
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;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Farhat Amine |
