How do I convert UTC date strings and delete T and Z in Java?
•
Java
I am using java 1.7
Attempt to convert:
2018-05-23T23:18:31.000Z
become
2018-05-23 23:18:31
Dateutils class:
public class DateUtils { public static String convertToNewFormat(String dateStr) throws ParseException { TimeZone utc = TimeZone.getTimeZone("UTC"); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss"); sdf.setTimeZone(utc); Date convertedDate = sdf.parse(dateStr); return convertedDate.toString(); } }
When trying to use it:
String convertedDate = DateUtils.convertToNewFormat("2018-05-23T23:18:31.000Z"); System.out.println(convertedDate);
Get the following exception:
Exception in thread "main" java.text.ParseException: Unparseable date: "2018-05-23T23:22:16.000Z" at java.text.DateFormat.parse(DateFormat.java:366) at com.myapp.utils.DateUtils.convertToNewFormat(DateUtils.java:7)
What could I have done wrong?
Is there a simpler method (such as Apache commons LIB)?
Solution
Try this You must use one mode for parsing and another mode for formatting
public static String convertToNewFormat(String dateStr) throws ParseException { TimeZone utc = TimeZone.getTimeZone("UTC"); SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); SimpleDateFormat destFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sourceFormat.setTimeZone(utc); Date convertedDate = sourceFormat.parse(dateStr); return destFormat.format(convertedDate); }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码