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


当前回答

简单来说。一个日历对象存储关于时区的信息,但是当你执行cal.getTime()时,时区信息将会丢失。所以对于时区转换,我建议使用DateFormat类…

其他回答

public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+date);
}

:

Calendar cal = Calendar.getInstance();

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

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

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

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

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

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()) );

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

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

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

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