Reputation: 3953
I am trying to convert my date in UTC format, for that I have to parse it using SimpleDateFormat class. But it is giving me Unparseable date exception. My code is given below:
//My date coming from server: Wed Dec 23 13:00:00 GMT+04:00 2015
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM EE- HH:mm:ss yy");
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date myDate = simpleDateFormat.parse(s1.datefrom + "");
Upvotes: 1
Views: 1718
Reputation: 338181
Apparently you want to parse a string that represents a moment with a wall-clock time four hours ahead of UTC, and then adjust into UTC wall-clock time.
OffsetDateTime.parse(
"Wed Dec 23 13:00:00 GMT+04:00 2015" ,
DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu" , Locale.US )
)
.toInstant() // Adjust from four hours ahead of UTC to UTC itself by extracting a `Instant`.
.toString()
2015-12-23T09:00:00Z
The modern approach uses the java.time classes rather than the terrible old java.time classes.
String input = "Wed Dec 23 13:00:00 GMT+04:00 2015" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM d HH:mm:ss OOOO uuuu" , Locale.US ) ;
OffsetDateTime odt = OffsetDateTime.parse( input , f ) ;
odt.toString(): 2015-12-23T13:00+04:00
If you want to adjust that into UTC, the simplest approach is to extract an Instant
. The Instant
class is always in UTC, by definition.
Instant instant = odt.toInstant() ;
Or, to retain the flexibility of OffsetDateTime
, call withOffsetSameInstant
. Pass the constant ZoneOffset.UTC
.
OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC ) ;
If you must use the awful legacy class java.util.Date
, convert from Instant
.
java.util.Date d = java.util.Date.from( instant ) ;
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
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
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.
Upvotes: 0
Reputation: 1530
I believe this should work :SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy",Locale.US);
Upvotes: 1