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


当前回答

这里还有一个获取GMT时间戳对象的建议:

import java.sql.Timestamp;
import java.util.Calendar;

...

private static Timestamp getGMT() {
   Calendar cal = Calendar.getInstance();
   return new Timestamp(cal.getTimeInMillis()
                       -cal.get(Calendar.ZONE_OFFSET)
                       -cal.get(Calendar.DST_OFFSET));
}

其他回答

转换UTC当前日期时间:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

DateTimeZone dateTimeZone = DateTimeZone.getDefault(); //Default Time Zone

DateTime currDateTime = new DateTime(); //Current DateTime

long utcTime = dateTimeZone.convertLocalToUTC(currDateTime .getMillis(), false);

String currTime = formatter.print(utcTime); //UTC time converted to string from long in format of formatter

currDateTime = formatter.parseDateTime(currTime); //Converted to DateTime in UTC

你可以使用:

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));

然后,使用aGMTCalendar对象执行的所有操作都将使用GMT时区完成,并且不会应用夏令时或固定偏移量。我认为之前的帖子是正确的,Date()对象总是返回GMT,直到你对Date对象做一些事情,它才被转换为本地时区。

这为我工作,返回格林尼治时间戳!

    Date currDate;
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    long currTime = 0;
    try {

        currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
        currTime = currDate.getTime();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

以下是乔恩·斯基特的回答中似乎不正确的地方。他说:

date始终使用UTC。你凭什么认为它是本地的 时间吗?我怀疑问题在于您通过 使用本地时区的Calendar实例,或者可能使用 Date.toString(),它也使用本地时区。

然而,代码:

System.out.println(new java.util.Date().getHours() + " hours");

给出的是本地时间,而不是GMT (UTC)时间,完全没有使用Calendar和SimpleDateFormat。

这就是为什么看起来有些事情是不正确的。

把这些回答放在一起,代码如下:

System.out.println(Calendar.getInstance(TimeZone.getTimeZone("GMT"))
                           .get(Calendar.HOUR_OF_DAY) + " Hours");

显示GMT时间而不是本地时间——请注意,getTime.getHours()缺失,因为这将创建一个Date()对象,该对象理论上以GMT存储日期,但返回本地时区的小时。

:

Calendar cal = Calendar.getInstance();

然后就可以得到当前的日期和时间。 您还可以获得当前日期和时间的时区:

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

你可以问cal.get(Calendar.DATE);或其他日历常量关于其他细节。 日期和时间戳在Java中已弃用。它不是日历类。