How to convert java.util.Date to GMT format

后端 未结 1 1004
温柔的废话
温柔的废话 2021-01-14 04:42

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

1条回答
  •  逝去的感伤
    2021-01-14 05:17

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

    0 讨论(0)
提交回复
热议问题