1

Hello there im receiveing from frontend a string who has this format (2018-04-12T03:00:00.000Z), so, i have to convert it to Date from Util package using Java.(java.util.Date)

Is there a good way to do this?

Sérgio Thiago Mendonça
  • 1,161
  • 2
  • 13
  • 23
  • What have you tried and what are you having trouble with? I assume you have looked up SimpleDateFormat ? – Peter Lawrey Jun 05 '18 at 10:40
  • Generally avoid the `Date` class. It is long outdated. In your case I recommend `Instant` from [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Jun 05 '18 at 13:25

2 Answers2

3

If you are using Java 8+, the easiest way is to use the java.time package to parse the date:

Date date = Date.from(Instant.parse("2018-04-12T03:00:00.000Z"));
assylias
  • 321,522
  • 82
  • 660
  • 783
0
String sDate1="2018-04-12T03:00:00.000Z";  
Date date1=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(sDate1);  
System.out.println(sDate1+"\t"+date1);  
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
Venki WAR
  • 1,997
  • 4
  • 25
  • 38
  • `Z` is an offset from UTC, and hardcoding as a literal in the format leads to incorrect results. Also please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class as the first option and without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Jun 05 '18 at 13:30
  • I tested this code in my IDE. It's working fine @OleV.V. – Venki WAR Jun 06 '18 at 03:35
  • Correct output on my computer in Europe/Copenhagen time zone would have been Thu Apr 12 05:00:00 CEST 2018. Your code prints `2018-04-12T03:00:00.000Z Thu Apr 12 03:00:00 CEST 2018`. It’s wrong by two hours. If your time zone happens to coincide with UTC, your output will happen to be correct. Your snippet produces wrong output on about 19 computers out of 20. – Ole V.V. Jun 06 '18 at 07:10
  • Which output did you get when you tested? – Ole V.V. Jun 07 '18 at 09:04