Reputation: 5379
I am doing simple String to date conversion in java, Only one thing i have to take care conversion should be in GMT. I am able to convert my String in GMT. But when i tried to convert that date into timestamp i got different value (Seems value is based on my local timezone).
public static void timeFun(String str) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String dateInString = "2015-07-10T09:54:31.000-04:00";
Date date = formatter.parse(dateInString);
SimpleDateFormat sdfAmerica = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
TimeZone tz = TimeZone.getTimeZone("GMT");
sdfAmerica.setTimeZone(tz);
String convertedDate = sdfAmerica.format(date); // Convert to String
// first
Date dateInGMT = sdfAmerica.parse(convertedDate);
System.out.println(convertedDate); // Output = 2015-07-10T13:54:31.000Z (Right)
Timestamp timestamp = new java.sql.Timestamp(dateInGMT.getTime());
System.out.println(timestamp); // Output = 2015-07-10 19:24:31.0 (Wrong)
}
Upvotes: 2
Views: 330
Reputation: 5379
This code is working fine for me:
public static Timestamp convertStringToTimestamp(String strRaw) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String dateInString = strRaw;
Date date = formatter.parse(dateInString);
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
formatter.setTimeZone(gmtTime);
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(date);
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Timestamp t = new Timestamp(formatter1.parse(formatter.format(calendar.getTime())).getTime());
System.out.println("********"+new Date(t.getTime()));
return new Timestamp(formatter1.parse(formatter.format(calendar.getTime())).getTime());
}
Upvotes: 0
Reputation: 338181
The answer by Alexander is correct.
These old date-time classes are an awful mess. Avoid them, as suggested in their JavaDoc. They have been supplanted by the java.time framework.
OffsetDateTime odt = OffsetDateTime.parse( "2015-07-10T09:54:31.000-04:00" );
To get UTC (GMT), extract a Instant
.
Instant instant = odt.toInstant();
To see the same moment through the lens of a particular time zone, apply a ZoneId
.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );
All of this has been covered many times on Stack Overflow.
Upvotes: 2
Reputation: 1421
Timestamp.toString() internally uses a Calendar instance with Default System Timezone. As you can see in Source Code java.util.Date.normalize() does the magic. So, yes ... The last System output is based on your local timezone.
Upvotes: 2