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 03:50

Use java.time package and include below code-

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

or

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

depending on your application need.

查看更多
心情的温度
3楼-- · 2018-12-31 03:50

Actually not time, but it's representation could be changed.

SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(f.format(new Date()));

Time is the same in any point of the Earth, but our perception of time could be different depending on location.

查看更多
墨雨无痕
4楼-- · 2018-12-31 03:53

This definitely returns UTC time: as String and Date objects !

static final String DATEFORMAT = "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(DATEFORMAT);
    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;
}
查看更多
只靠听说
5楼-- · 2018-12-31 03:54

this is my implementation:

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();    
}
查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 03:55

Here is another way to get GMT time in String format

String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss z" ;
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String dateTimeString =  sdf.format(new Date());
查看更多
只若初见
7楼-- · 2018-12-31 03:55

If you want to avoid parsing the date and just want a timestamp in GMT, you could use:

final Date gmt = new Timestamp(System.currentTimeMillis()
            - Calendar.getInstance().getTimeZone()
                    .getOffset(System.currentTimeMillis()));
查看更多
登录 后发表回答