nfvindaloo
nfvindaloo

Reputation: 938

Read date without timezone information

I receive datetime strings with no timezone qualifier in the format:

2014-01-30 07:48:25

I know that the strings are produced by a server in Florida. Is there a way using java.util or joda Date libs to specify that the date is from Florida then parse it with the appripriate UTC offset, depending on where it falls in the calendar for daylight savings time?

Upvotes: 3

Views: 16567

Answers (3)

jalopaba
jalopaba

Reputation: 8129

Just to complete previous answers. The same funcionality with Joda-Time:

DateTime dateTime = DateTime.parse("2014-01-30 07:48:25", DateTimeFormat
   .forPattern("yyyy-MM-dd HH:mm:ss")
   .withZone(DateTimeZone.forID("America/New_York")));
System.out.println(dateTime);
System.out.println(dateTime.withZone(DateTimeZone.UTC));
System.out.println(dateTime.withZone(DateTimeZone.forID("Europe/Madrid")));

---

2014-01-30T07:48:25.000-05:00
2014-01-30T12:48:25.000Z
2014-01-30T13:48:25.000+01:00

Upvotes: 2

StoopidDonut
StoopidDonut

Reputation: 8617

Assuming you are referring to the part of Florida following EST, you can set the timezone for SimpleDateFormat and set your TimeZone to EST.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
Date date = format.parse("2014-01-30 07:48:25");

Your parsed date now can be utilized by your default TimeZone of the system (or set it to your liking as we did in the first place).

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
System.out.println(date);

The output I get for your date offset to UTC:

Thu Jan 30 12:48:25 UTC 2014

Upvotes: 3

Ralf
Ralf

Reputation: 6853

You can provide a "source timezone" to an instance of SimpleDateFormat and the to-be-parsed date string is then converted to your local/default timezone.

TimeZone timeZone = TimeZone.getTimeZone("America/New_York")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
sdf.setTimeZone(getTimeZone(source));

Be careful when providing the time zone name. TimeZone will silently fail over to GMT if you pass in a string it does not understand as a timezone.

Upvotes: 2

Related Questions