How do I display a date with a custom timezone?

Kyle Boon picture Kyle Boon · Jul 22, 2009 · Viewed 29.1k times · Source

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);

Answer

Jon Skeet picture Jon Skeet · Jul 22, 2009

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