当我创建一个新的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

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

其他回答

如果你想要一个Date对象,字段调整为UTC,你可以用Joda Time这样做:

import org.joda.time.DateTimeZone;
import java.util.Date;

...

Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));

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

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存储日期,但返回本地时区的小时。

SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));
public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+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();
    }