views:

417

answers:

2

Lets say I have a string that represents a date that looks like this:

"Wed Jul 08 17:08:48 GMT 2009"

So I parse that string into a date object like this:

DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy");
Date fromDate = (Date)formatter.parse(fromDateString);

That gives me the correct date object. Now I want to display this date as a CDT value.

I've tried many things, and I just can't get it to work correctly. There must be a simple method using the DateFormat class to get this to work. Any advice? My last attempt was this:

formatter.setTimeZone(toTimeZone);
String result = formatter.format(fromDate);
+4  A: 

Use "zzz" instead of "ZZZ": "Z" is the symbol for an RFC822 time zone.

DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

Having said that, my standard advice on date/time stuff is to use Joda Time, which is an altogether better API.

EDIT: Short but complete program:

import java.text.*;
import java.util.*;

public class Test
{
    public List<String> names;

    public static void main(String [] args)
        throws Exception // Just for simplicity!
    {
        String fromDateString = "Wed Jul 08 17:08:48 GMT 2009";
        DateFormat formatter = new SimpleDateFormat
            ("EEE MMM dd HH:mm:ss zzz yyyy");
        Date fromDate = (Date)formatter.parse(fromDateString);
        TimeZone central = TimeZone.getTimeZone("America/Chicago");
        formatter.setTimeZone(central);
        System.out.println(formatter.format(fromDate));
    }
}

Output: Wed Jul 08 12:08:48 CDT 2009

Jon Skeet
Sadly I can't add another dependency without more red tape that I want to deal with. There must be a way to format the time zones using standard java libraries.
Kyle Boon
There is, as given in the answer. Just expect more pain if you have to any other date/time manipulation.
Jon Skeet
Its not helping. The formatter always spits out the time in GMT and not the reqeusted CDT.
Kyle Boon
Then you're using the wrong time zone - it worked fine in my test case. I'll add a short but complete program to demonstrate.
Jon Skeet
Yeah, you were right... man that's a pain. Had the correct code the whole time and a typo in my unit test prevented it from working correctly.
Kyle Boon
+1  A: 

Using:

formatter.setTimeZone(TimeZone.getTimeZone("US/Central"));

outputs:

Wed Jul 08 12:08:48 CDT 2009

for the date in your example on my machine. That is after substituting zzz for ZZZ in the format string.

laz