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


当前回答

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

//Local time zone   
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

//Time in GMT
return dateFormatLocal.parse( dateFormatGmt.format(new Date()) );

其他回答

这里还有一个获取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时间:作为字符串和日期对象!

static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

public static Date getUTCdatetimeAsDate() {
    // note: doesn't check for null
    return stringDateToDate(getUTCdatetimeAsString());
}

public static String getUTCdatetimeAsString() {
    final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    final String utcTime = sdf.format(new Date());

    return utcTime;
}

public static Date stringDateToDate(String StrDate) {
    Date dateToReturn = null;
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATEFORMAT);

    try {
        dateToReturn = (Date)dateFormat.parse(StrDate);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }

    return dateToReturn;
}

date没有特定的时区,尽管它的值通常被认为与UTC有关。你凭什么认为现在是当地时间?

准确地说:java.util.Date中的值是自Unix epoch(发生在UTC时间1970年1月1日午夜)以来的毫秒数。同样的纪元也可以用其他时区来描述,但是传统的描述是用UTC来表示的。因为它是从一个固定的纪元开始的毫秒数,所以java.util.Date中的值在世界各地的任何特定时刻都是相同的,而不考虑当地的时区。

我怀疑问题是您通过使用本地时区的Calendar实例来显示它,或者可能使用同样使用本地时区的Date.toString(),或者默认情况下也使用本地时区的SimpleDateFormat实例。

如果这不是问题,请发布一些示例代码。

不过,我还是建议您使用Joda-Time,它提供了更清晰的API。

当前UTC日期

Instant.now().toString().replaceAll("T.*", "");

使用java。时间包和包括以下代码-

ZonedDateTime now = ZonedDateTime.now( ZoneOffset.UTC );

or

LocalDateTime now2 = LocalDateTime。now (ZoneOffset。UTC);

这取决于您的应用程序需要。