How can I get the current date and time in UTC or

2018-12-31 03:47发布

When I create a new Date object, it is initialized to the current time but in the local timezone. How can I get the current date and time in GMT?

30条回答
怪性笑人.
2楼-- · 2018-12-31 04:04

Here is my implementation of toUTC:

    public static Date toUTC(Date date){
    long datems = date.getTime();
    long timezoneoffset = TimeZone.getDefault().getOffset(datems);
    datems -= timezoneoffset;
    return new Date(datems);
}

There's probably several ways to improve it, but it works for me.

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 04:04

This code prints the current time UTC.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;


public class Test
{
    public static void main(final String[] args) throws ParseException
    {
        final SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
        f.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(f.format(new Date()));
    }
}

Result

2013-10-26 14:37:48 UTC
查看更多
无色无味的生活
4楼-- · 2018-12-31 04:05
public static void main(String args[]){
    LocalDate date=LocalDate.now();  
    System.out.println("Current date = "+date);
}
查看更多
孤独总比滥情好
5楼-- · 2018-12-31 04:06

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); Then all operations performed using the aGMTCalendar object will be done with the GMT time zone and will not have the daylight savings time or fixed offsets applied

Wrong!

Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
aGMTCalendar.getTime(); //or getTimeInMillis()

and

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

will return the same time. Idem for

new Date(); //it's not GMT.
查看更多
爱死公子算了
6楼-- · 2018-12-31 04:11
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(date));
查看更多
其实,你不懂
7楼-- · 2018-12-31 04:13

Just to make this simpler, to create a Date in UTC you can use Calendar :

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

Which will construct a new instance for Calendar using the "UTC" TimeZone.

If you need a Date object from that calendar you could just use getTime().

查看更多
登录 后发表回答