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


当前回答

这是我的实现:

public static String GetCurrentTimeStamp()
{
    Calendar cal=Calendar.getInstance();
    long offset = cal.getTimeZone().getOffset(System.currentTimeMillis());//if you want in UTC else remove it .
    return new java.sql.Timestamp(System.currentTimeMillis()+offset).toString();    
}

其他回答

你可以使用的简单函数:

编辑:这个版本使用现代java。时间类。

private static final DateTimeFormatter FORMATTER
        = DateTimeFormatter.ofPattern("dd-MM-uuuu HH:mm:ss z");

public static String getUtcDateTime() {
    return ZonedDateTime.now(ZoneId.of("Etc/UTC")).format(FORMATTER);
}

方法返回值:

26-03-2022 17:38:55 UTC

最初的功能:

 public String getUTC_DateTime() {
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss z");
    dateTimeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));//gmt
    return dateTimeFormat.format(new Date());

}

以上函数返回:

26-03-2022 08:07:21 UTC 

为了简单起见,你可以使用Calendar来创建一个UTC Date:

Calendar.getInstance(TimeZone.getTimeZone("UTC"));

它将使用“UTC”时区为Calendar构造一个新实例。

如果需要该日历中的Date对象,可以使用getTime()。

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

long instant = DateTimeZone.UTC.getMillisKeepLocal(DateTimeZone.getDefault(), System.currentTimeMillis());
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));

转换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