用Java获取GMT时间

问题描述 投票:26回答:10

在Java中,我想获得GMT的当前时间。

我试过这样的各种选项:

Date date = new Date();
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
date1 = calendar.getTime();

但是日期总是在我当地的时区解释。

我做错了什么以及如何将java Date转换为GMT?

java date gmt
10个回答
34
投票

很有可能你在获得日期时在后端做了正确的事情,但没有任何迹象表明你没有采用GMT时间并根据你机器当前的语言环境进行格式化。

final Date currentTime = new Date();

final SimpleDateFormat sdf =
        new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");

// Give it to me in GMT time.
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("GMT time: " + sdf.format(currentTime));

关键是要使用自己的DateFormat,而不是系统提供的。这样您就可以将DateFormat的时区设置为您想要的时区,而不是将其设置为Locale的时区。


0
投票

在java 8之后,您可能希望获得格式化时间,如下所示:

DateTimeFormatter.ofPattern("HH:mm:ss.SSS").format(LocalTime.now(ZoneId.of("GMT")));

18
投票

我想知道为什么没有人这样做:

Calendar time = Calendar.getInstance();
time.add(Calendar.MILLISECOND, -time.getTimeZone().getOffset(time.getTimeInMillis()));
Date date = time.getTime();

更新:自Java 8,9,10及更多版本以来,Java应该有更好的替代方案。感谢您对@humanity的评论


6
投票

根据我的经验,Java中捆绑的Calendar和Date类可以产生不良效果。如果您不介意升级到Java 8,请考虑使用ZonedDateTime

像这样:

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

5
投票

tl;dr

Instant.now()

java.time

Answer by Damilola建议你使用Java 8及更高版本中内置的java.time框架是正确的。但是,如果您只想要UTC而不是任何特定的时区,那么该答案使用ZonedDateTime类是过度的。

麻烦的旧日期时间类现在已经遗留下来,取而代之的是java.time类。

Instant

Instant类代表UTC时间轴上的一个时刻,分辨率为nanoseconds(小数部分最多九(9)位)。

简单代码:

Instant instant = Instant.now() ;

instant.toString():2016-11-29T23:18:14.604Z

您可以将Instant视为可以添加时区(ZoneID)以获得ZonedDateTime的构建块。

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

About java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,如java.util.DateCalendarSimpleDateFormat

Joda-Time项目,现在在maintenance mode,建议迁移到java.time。

要了解更多信息,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规格是JSR 310

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展了java.time。该项目是未来可能添加到java.time的试验场。你可能会在这里找到一些有用的类,如IntervalYearWeekYearQuartermore


3
投票

要获得GMT所需的时间,您需要的是

long millis = System.currentTimeMillis();

你也可以

long millis = new Date().getTime();

long millis = 
    Calendar.getInstance(TimeZone.getTimeZone("GMT")).getTimeInMillis();

但这些是进行相同呼叫的低效方式。


2
投票

在尝试了很多方法后,我发现,为了在GMT中获得毫秒时间,您需要创建两个单独的SimpleDateFormat对象,一个用于格式化GMT,另一个用于解析。

这是代码:

 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 format.setTimeZone(TimeZone.getTimeZone("UTC"));
 Date date = new Date();
 SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 Date dateTime= dateParser.parse(format.format(date));
 long gmtMilliSeconds = dateTime.getTime();

这很好用。 :)


1
投票

你不能

首先,你在问不可能。没有老式的Date物体,因为没有时区或GMT偏移。

但是日期总是在我当地的时区解释。

我想你已经打印了Date或做了一些隐含称为toString方法的东西。我相信这是唯一一次在你的时区解释Date。更准确地说,在JVM的当前默认时区中。另一方面,这是不可避免的。 Date.toString()确实以这种方式运行,它获取JVM的时区设置并使用它来呈现要返回的字符串。

你可以用java.time

但是你不应该使用Date。那个班级设计很差,幸运的是已经过时了。 java.time是替换它的现代Java日期和时间API,它有一个或两个类别用于日期和时间,偏离GMT或UTC。我现在正在考虑GMT和UTC的同义词,严格来说它们不是。

    OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
    System.out.println("Time now in UTC (GMT) is " + now);

刚刚运行此代码片段时,输出结果如下:

UTC(格林尼治标准时间)时间是2019-06-17T11:51:38.246188Z

输出的尾随Z表示UTC。

链接


0
投票

这非常简单直接。

Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

现在日期将包含当前的GMT时间。


0
投票

以下有用的Utils方法用于管理GMT中的时间和DST节省:

public static Date convertToGmt(Date date) {
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date(date.getTime() - tz.getRawOffset());

    // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
    if (tz.inDaylightTime(ret)) {
        Date dstDate = new Date(ret.getTime() - tz.getDSTSavings());

        // check to make sure we have not crossed back into standard time
        // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
        if (tz.inDaylightTime(dstDate)) {
            ret = dstDate;
        }
    }
    return ret;
}

public static Date convertFromGmt(Date date) {
    TimeZone tz = TimeZone.getDefault();
    Date ret = new Date(date.getTime() + tz.getRawOffset());

    // if we are now in DST, back off by the delta.  Note that we are checking the GMT date, this is the KEY.
    if (tz.inDaylightTime(ret)) {
        Date dstDate = new Date(ret.getTime() + tz.getDSTSavings());

        // check to make sure we have not crossed back into standard time
        // this happens when we are on the cusp of DST (7pm the day before the change for PDT)
        if (tz.inDaylightTime(dstDate)) {
            ret = dstDate;
        }
    }
    return ret;
}
© www.soinside.com 2019 - 2024. All rights reserved.