How can I convert the date "Mon Jul 01 08:00:00 IST 2019" of type string to ISODate "2019-07-01T03:00:00.000Z"?
Asked
Active
Viewed 1.4k times
1
-
2What have you tried ? SO is not a coding service, and without some code from yourself, the question will be closed in minutes – azro Jun 29 '19 at 09:53
-
This seems poorly researched? [Convert Date to ISO 8601 String in Java](https://mincong-h.github.io/2017/02/16/convert-date-to-string-in-java/), for example. – Ole V.V. Jun 29 '19 at 10:46
-
For most purposes you should not want to convert a datetime string in one format to another format. Instead inside your program you should keep date and time in a proper date-time object, for example `ZonedDateTime` or `Instant`. Only when you need to give out a string, format your date and time into one. – Ole V.V. Jun 29 '19 at 10:52
1 Answers
7
Update: Using DateTimeFormat, introduced in java 8:
The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'". The trailing Z is the interesting part. Usually there's time zone data here, like -0700. So the pattern would be ...Z, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy". Mind the small y -s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
Original answer - with old API SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
Kiran Mistry
- 3,376
- 2
- 8
- 28