0

I need to transform a Twitter timestampe into a Java Date object, here is an example of a value of a Timestampe: "2015-01-06T21:07:00Z"

Can you please give me sample of java code (standard Java) doing the job?

Thank you

Mano Jad
  • 17
  • 4
  • Take a look at [SimpleDateFormat](https://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html) and try to format the date to match that output. – clinomaniac Mar 23 '18 at 18:21
  • 1
    @clinomaniac The `SimpleDateFormat` class was supplanted by the [`DateTimeFormatter`](https://docs.oracle.com/javase/9/docs/api/java/time/format/DateTimeFormatter.html) class years ago. All the troublesome old legacy date-time classes are made obsolete by the *java.time* classes. – Basil Bourque Mar 23 '18 at 18:59
  • Search Stack Overflow before posting a Question. All the basic date-time issues have been asked and answered. – Basil Bourque Mar 23 '18 at 19:05

2 Answers2

2

I recommend you take advantage of the new Date/Time API introduced in Java 8, specifically Instant as follows:

Instant.parse("2015-01-06T21:07:00Z");

You can then perform a multitude of operations, but keep in mind that the object is immutable, so any changes to the instance (that aren't chained) must be stored in a separate variable.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
0

Actually it is ISO 8601 format for UTC time zone.

It conforms with XML DateTime format as well. So, to get actual java.util.Calendar or java.util.Date out of it you simply can use available in JDK

Calendar twitterCalendar = javax.xml.bind.DatatypeConverter.parseDateTime("2015-01-06T21:07:00Z");
Date twitterDate = javax.xml.bind.DatatypeConverter.parseDateTime("2015-01-06T21:07:00Z").getTime();

Just be aware: java.util.Date has no Time Zone information in it. Your string is in UTC, so if you try to print value of twitterDate you will see Date/Time in TimeZone of your computer/server. Still actual value of twitterDate stays the same

millisecond value that is an offset from the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).

Vadim
  • 4,027
  • 2
  • 10
  • 26