I have Service
fetch date string from web and then I want to pare it to Date
object. But somehow application crashes.
This is my string that I\'m parsi
long millisecondsSinceEpoch = OffsetDateTime.parse( "2015-02-05T05:20:02+00:00" ).plusHour( 1 ).toInstant().toEpochMilli() // Warning: Possible loss of data in truncating nanoseconds to milliseconds. But not in this particular case.
Other answers are correct but now outdated. The old date-time classes are now legacy. Use java.time classes instead.
The input String is in standard ISO 8601 format. Parse directly, no need to define a formatting pattern as the java.time classes use ISO 8601 formats by default.
OffsetDateTime
The input includes an offset-from-UTC with the +00:00
so we can parse as an OffsetDateTime object.
String input = "2015-02-05T05:20:02+00:00" ;
OffsetDateTime odt = OffsetDateTime.parse( input );
If you want to add an hour or a minute later to set an alarm, call the plus
methods.
OffsetDateTime minuteLater = odt.plusMinutes( 1 );
OffsetDateTime hourLater = odt.plusHours( 1 );
To get a count of milliseconds, go through the Instant
class. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. Asking for milliseconds means possible data loss as the nine digits of a decimal fraction get truncated to the three digits of decimal fraction.
long millisecondsSinceEpoch = odt.toInstant().toEpochMilli(); // Warning: Possible loss of data in truncating nanoseconds to milliseconds.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome 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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.