How do I display a date with a custom timezone?

后端 未结 4 1291
闹比i
闹比i 2021-02-13 09:28

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:

4条回答
  •  庸人自扰
    2021-02-13 10:04

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

提交回复
热议问题