当我创建一个新的Date对象时,它被初始化为当前时间,但在本地时区。如何获得当前的GMT日期和时间?


当前回答

public class CurrentUtcDate 
{
    public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println("UTC Time is: " + dateFormat.format(date));
    }
}

输出:

UTC Time is: 22-01-2018 13:14:35

您可以根据需要更改日期格式。

其他回答

如果你正在使用joda time,并希望当前时间以毫秒为单位,不需要本地偏移量,你可以使用这个:

long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());

其实不是时间,而是它的表现形式可以改变。

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));

地球上任何地方的时间都是一样的,但我们对时间的感知可能会因地点的不同而不同。

当我需要输出一个Date对象时,这就是我这样做的方式,通常情况下,您需要在SQL数据库中保存一个日期,而我希望它是UTC。我只是减去当地时区的偏移时间。

    ZonedDateTime now = ZonedDateTime.now();
    Date nowUTC = new Date(1000 * (now.toEpochSecond() - now.getOffset().getTotalSeconds()));

- - -更新 巴兹尔建议用一种更清洁的方式来达到同样的效果

    Date nowUTC = Date.from(ZonedDateTime.now().toInstant());

但是在非utc java系统环境中测试后,我看到结果并不相同。根据巴兹尔的代码,日期仍然在本地区域

下面是另一种以字符串格式获取GMT时间的方法

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());

日历aGMTCalendar = Calendar. getinstance (TimeZone.getTimeZone("GMT")); 然后,使用aGMTCalendar对象执行的所有操作都将使用GMT时区完成,并且不会应用夏令时或固定偏移量

错了!

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()

and

Calendar aNotGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT-2"));aNotGMTCalendar.getTime();

会在同一时间回来。同上的对

new Date(); //it's not GMT.