Подтвердить что ты не робот

Как конвертировать локальную дату в GMT

Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
java.util.Date fromDate = cal.getTime();
System.out.println(fromDate);

Приведенный выше код не печатает дату в GMT, а скорее печатает в локальном часовом поясе. Как получить эквивалентную дату GMT с текущей даты (при условии, что программа может работать в Японии или SFO)

4b9b3361

Ответ 1

Как насчет этого -

public static void main(String[] args) throws IOException {
    Test test=new Test();
    Date fromDate = Calendar.getInstance().getTime();
    System.out.println("UTC Time - "+fromDate);
    System.out.println("GMT Time - "+test.cvtToGmt(fromDate));
}
private  Date cvtToGmt( Date date ){
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date( date.getTime() - tz.getRawOffset() );

    // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
    if ( tz.inDaylightTime( ret )){
        Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

        // check to make sure we have not crossed back into standard time
        // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
        if ( tz.inDaylightTime( dstDate )){
            ret = dstDate;
        }
     }
     return ret;
}

Результат тестирования:
Время UTC - Вт май 15 16:24:14 IST 2012
Время по Гринвичу - Вт май 15 10:54:14 IST 2012

Ответ 2

DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("Current DateTime in GMT : " + gmtFormat.format(new Date()));

В более общем плане вы можете конвертировать в любой (действительный) часовой пояс таким образом


См.

Ответ 3

Как этот SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));?