Java 如何获得格林威治标准时间的当前时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3001053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:27:32  来源:igfitidea点击:

How to get the current time in GMT?

javadategmt

提问by user353682

Possible Duplicate:
How can I get the current date and time in UTC or GMT in Java?

可能的重复:
如何在 Java 中以 UTC 或 GMT 形式获取当前日期和时间?

I want to get the current timestamp in GMT; any ideas how to do that?

我想以格林威治标准时间获取当前时间戳;任何想法如何做到这一点?



i managed to get a string in gmt format the problem is that i want to convert this string to equivalent timestamp object i.e same time but as a timestamp object

我设法得到一个 gmt 格式的字符串问题是我想将此字符串转换为等效的时间戳对象,即同一时间但作为时间戳对象

SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date date=new Date();
        String s=sdf.format(date);
        System.out.println("GMT: "+s);
        //need to convert the string to equivalent timestamp object

回答by Mark Peters

new Date().getTime();

Or just

要不就

System.currentTimeMillis();

Both assume you take "timestamp" to mean "milliseconds from the Unix epoch". Otherwise, clarify your question.

两者都假设您将“时间戳”表示为“Unix 纪元的毫秒数”。否则,请澄清您的问题。

Edit:In response to the comment/clarification/"answer":

编辑:回应评论/澄清/“答案”:

You're misunderstanding the difference between storinga GMT timestamp and displayingit as such. Date/Timestamp will store as milliseconds from the UTC epoch internally, and is not related to a certain timezone, since timestamps are the same regardless of your timezone. If it's 10pm GMT in Honolulu, it's also 10pm GMT in New York. They have the same timestamp, though your location might make them render differently.

您误解了存储GMT 时间戳和显示它之间的区别。日期/时间戳将在内部存储为 UTC 纪元的毫秒数,并且与特定时区无关因为无论您的时区如何,时间戳都是相同的。如果火奴鲁鲁是格林威治标准时间晚上 10 点,那么纽约也是格林威治标准时间晚上 10 点。它们具有相同的时间戳,但您的位置可能会使它们呈现不同的效果。

A Calendar, on the other hand, is meant for displaying certain fieldsproperly (as in, it's 6pm on the 8th of June) and so doeshave an internal notion of TimeZone (since 6pm EDT is NOT the same time as 6pm PDT).

另一方面,日历旨在正确显示某些字段(例如,6 月 8 日下午 6 点),因此确实具有时区的内部概念(因为美国东部时间下午 6 点与太平洋时间下午 6 点不同)。

Anyway, your example gave a SimpleDateFormat. If you want to displayyour already-GMT Timestamp in GMT, do the same thing and pass in the Timestamp.

无论如何,您的示例给出了 SimpleDateFormat。如果您想在 GMT 中显示您已经是 GMT 的时间戳,请执行相同的操作并传入时间戳。

    Timestamp timestamp = new Timestamp(System.currentTimeMillis());
    SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss.SS");
    fmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    System.out.println(fmt.format(timestamp));

回答by dty

new Date()

...since all Date objects are GMT based.

...因为所有 Date 对象都是基于 GMT 的。