Java获取UTC时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34484745/
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-11 15:41:50  来源:igfitidea点击:

Java get UTC time

javadatetimejava-8

提问by user2924127

I want to get the time in UTC time zone. So I wrote the code:

我想获取 UTC 时区的时间。于是我写了代码:

import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;

public class RegularSandbox {

    public static void main(String[] args) {

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

        System.out.println("DATETIME = " + Date.from(utc.toInstant()));

    }
}

The problem is the output shows me the time in PST (my local timezone). I need it to output the time in UTC so I can store it inside of my databases.

问题是输出显示了 PST(我的本地时区)中的时间。我需要它以 UTC 格式输出时间,以便我可以将它存储在我的数据库中。

采纳答案by LowLevel

System.out.println("DATETIME = " + utc.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

回答by jjurm

I suggest you to use Joda-Time.

我建议你使用Joda-Time

DateTime dt = new DateTime(DateTimeZone.UTC);

回答by m.aibin

ZonedDateTime utc = ZonedDateTime.now(ZoneOffset.UTC);
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z"); // you can specify format that you want to get
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(utc));

回答by Meno Hochschild

You do too much when trying to convert to old java.util.Date. And then you implicitly use its method toString()which should be well known for the observed behaviour to print the instant always in your system timezone.

尝试转换为 old 时您做得太多了java.util.Date。然后你隐式地使用它的方法toString(),它应该以观察到的行为而闻名,总是在你的系统时区打印瞬间。

But printing in UTC timezone is extremely simple, not even a formatter is needed if you can cope with ISO-8601-notation:

但是以 UTC 时区打印非常简单,如果您可以处理 ISO-8601 表示法,甚至不需要格式化程序:

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

System.out.println("DATETIME = " + utc.toInstant());
// output: DATETIME = 2015-12-30T15:01:18.483Z (Instant is always printed with UTC offset)

System.out.println("DATETIME = " + utc);
// output: DATETIME = 2015-12-30T15:01:57.611Z (the same because you 
// have explicitly set the UTC Offset when constructing the ZonedDateTime)

You see, the behaviour of toString()of the new Java-8 classes Instantand ZonedDateTimeis much clearer and is always in ISO-format. No need for a confusing conversion to Date.

你看,行为toString()的新的Java-8类的InstantZonedDateTime更清晰,总是在ISO格式。无需对Date.

About specialized formatters, you will only need one if you intend to deviate from ISO-8601-format - maybe using localized month names or extra printing of weekdays etc. Example in US-style:

关于专门的格式化程序,如果您打算偏离 ISO-8601 格式,则只需要一个 - 可能使用本地化的月份名称或工作日的额外打印等。美国风格的示例:

System.out.println(
  "DATETIME = " 
  + utc.format(DateTimeFormatter.ofPattern("MM/dd/uuuu h:mm:ss a xxx")));
// output: DATETIME = 12/30/2015 3:14:50 PM +00:00

Note that the answer of @LowLevel uses a wrong pattern. If you leave out the symbol a (AM/PM-marker) then you should not choose the half-day-hour-symbol h but H (24-hour-format). And the timezone or offset symbol (here x) is crucial because otherwise the printed datetime will not be automatically recognized as being in UTC timezone.

请注意,@LowLevel 的答案使用了错误的模式。如果省略符号 a(上午/下午标记),则不应选择半天小时符号 h,而应选择 H(24 小时格式)。时区或偏移量符号(此处为 x)至关重要,否则打印的日期时间将不会被自动识别为 UTC 时区。

回答by Naresh

        private Calendar getUTCTime(){
            Calendar calendar = Calendar.getInstance();
            // Assuming your time is in utc + 8
            calendar.add(Calendar.HOUR, -8);
            return calendar;
        }