简体   繁体   中英

How to convert java.util.Date to GMT format

I have a string "2014-07-02T17:12:36.488-01:00" which shows the Mountain time zone. I parsed this into java.util.date format. Now I need to convert this to GMT format. Can anyone help me??

  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Object dd = null;
    try {
         dd=sdf.parseObject("2014-07-02T17:12:36.488-01:00");
        System.out.println(dd);
    } catch (ParseException e) {
        e.printStackTrace();`enter code here`
    }
    SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
System.out.println("Current Date and Time in GMT time zone:+ gmtDateFormat.format(dd));

There are a few problems in your code. For example, the format string doesn't match the actual format of the string you are parsing.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
Object dd = null;
try {
    dd = sdf.parse("2014-07-02T17:12:36.488-01:00");
    System.out.println(dd);
} catch (ParseException e) {
    e.printStackTrace();
}

SimpleDateFormat gmtDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssX");
gmtDateFormat.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));

System.out.println("Current Date and Time in GMT time zone:" + gmtDateFormat.format(dd));

To print the current date in whatever timezone you like, set the timezone you want to use on the SimpleDateFormat object. For example:

// Create a Date object set to the current date and time
Date now = new Date();

DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(now));

df.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Current date and time in IST: " + df.format(now));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM