Reputation: 543
I'm trying to convert this date string 2014-07-17T22:41:17+0000 to a timestmap, similar to this: 1405645259000.
I've tried something similar to this:
String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date);
How do I convert this (2014-07-17T22:41:17+000) to a Date? What is the correct format? I'm at a loss.
Upvotes: 0
Views: 116
Reputation: 338516
OffsetDateTime.parse( "2014-07-17T22:41:17+0000" )
.toInstant()
.toEpochMilli()
java.util.Date
Your question is easy in Joda-Time or the new java.time package in Java 8. Avoid java.util.Date and .Calendar as they are notoriously troublesome.
Your String is in standard format, complying with ISO 8601. Both libraries mentioned above use ISO 8601 as their defaults for parsing and generating strings.
The OffsetDateTime
class represents a moment on the timeline with an offset-from-UTC and with a resolution in nanoseconds.
OffsetDateTime odt = OffsetDateTime.parse( "2014-07-17T22:41:17+0000" );
From there you can ask for the count-of-milliseconds-since-epoch via the Instant
class. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli();
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, .Calendar
, & java.text.SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Example code on Joda-Time 2.3.
long millisSinceEpoch = new DateTime( "2014-07-17T22:41:17+0000" ).getMillis();
Upvotes: 1
Reputation: 698
Take a look at http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Your date string has the same format as
yyyy-MM-dd'T'HH:mm:ssZ //Eg: 2001-07-04T12:08:56-0700
So, your code should be:
String string = "2014-07-17T22:41:17+0000";
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH).parse(string);
System.out.println(date);
Upvotes: 6
Reputation: 69440
use this pattern:
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH).parse(string);
Upvotes: 3