Java设置的时区不默认为gmt + 0 [英] Java set timezone does not default to gmt+0

查看:45
本文介绍了Java设置的时区不默认为gmt + 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码.Java日期时间的字符串形式为gmt + 0.因此,我需要稍后根据不同的本地时区进行转换,但是当我尝试设置默认时区时,它会继续返回另外8个小时,因为我的机器在gmt + 8上.输出显示给我2017-12-09 09:00:00,但我想保留为2017-12-09 17:00:00,因为这是gmt + 0.

I have the following codes. The string form of the java date time is gmt+0. Thus I need to later convert it according to different local timezone but when I try to set the default timezone it keep going back another 8 hours cause my machine is on gmt+8.The output is showing me 2017-12-09 09:00:00 but I want to remain as 2017-12-09 17:00:00 because this is gmt+0.

    String existingTime = "2017-12-09 17:00:00";
    String newTime = "2017-12-09 14:00:00";

    Date existingDateTime = null;
    Date newDateTime = null;
    Date localexistingDateTime = null;
    Date localnewDateTime = null;
    DateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    TimeZone tz = TimeZone.getDefault();
    sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
    // sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:30"));

    try {
        existingDateTime = dateTimeFormat.parse(existingTime);
        newDateTime = dateTimeFormat.parse(newTime);

        System.out.println("GMT existingDateTime" + sdf.format(existingDateTime));
        System.out.println("GMT newDateTime" + sdf.format(newDateTime));
    } catch (ParseException ex) {
        System.out.println("MyError:Parse Error has been caught for date parse close");
        ex.printStackTrace(System.out);
    }

推荐答案

此代码段可能使您开始使用现代Java日期和时间API java.time .在首先描述的 Java规范请求之后,它也被称为JSR-310.它.

This snippet may get you started using java.time, the modern Java date and time API. It is also known as JSR-310 after the Java Specification Request that first described it.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
    String existingTime = "2017-12-09 17:00:00";
    OffsetDateTime existingDateTime = LocalDateTime.parse(existingTime, formatter)
            .atOffset(ZoneOffset.UTC);
    System.out.println("UTC existingDateTime: " + existingDateTime.format(formatter));
    System.out.println("Pyongyang existingDateTime: " 
            + existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Pyongyang"))
                    .format(formatter));
    System.out.println("Singapore existingDateTime: " 
            + existingDateTime.atZoneSameInstant(ZoneId.of("Asia/Singapore"))
                    .format(formatter));

运行该代码段的输出是:

The output from running the snippet is:

UTC existingDateTime: 2017-12-09 17:00:00
Pyongyang existingDateTime: 2017-12-10 01:30:00
Singapore existingDateTime: 2017-12-10 01:00:00

这是我在计算机上获得的输出(在欧洲/柏林时区),但是使现代类独立于JVM的时区更容易,因此您应该在计算机上获得相同的输出.

This was the output I got on my computer (in Europe/Berlin time zone), but it’s easier to keep the modern classes independent of the JVM’s time zone, so you should get the same output on your computer.

编辑:您在评论中询问是否无法使用GMT + 09:00的偏移量而不是时区.我不确定您为什么要这么做,因为真实的人生活在时区而不是偏移中,但是当您知道如何时,这很容易:

EDIT: You asked in a comment if it isn’t possible to use an offset of GMT+09:00 instead of a time zone. I’m unsure why you will want to do that since real people live in time zones rather than in offsets, but it’s easy when you know how:

    System.out.println("GMT+09:00 existingDateTime: "
            + existingDateTime.withOffsetSameInstant(ZoneOffset.ofHours(9))
                    .format(formatter));

输出:

GMT+09:00 existingDateTime: 2017-12-10 02:00:00

LocalDateTime 是没有时区或偏移信息的日期和时间.由于您的字符串不包含偏移量或区域,因此我将其用于解析.并且由于您告诉我您的日期时间是格林尼治标准时间+0,因此我将其转换为带有偏移UTC的 OffsetDateTime .从那里可以直接将其转换为不同的本地时区.因此,我演示了几个时区,每次都使用与我解析时使用的格式相同的格式来格式化日期时间,因为我收集到的是,您倾向于喜欢 yyyy-MM-dd HH:mm:ss 格式.

A LocalDateTime is a date and time without time zone or offset information. Since your string doesn’t contain offset or zone, I use this for parsing. And since you told me your date-time was in GMT+0, I convert it to an OffsetDateTime with offset UTC first thing. From there it’s straightforward to convert it into different local time zones. So I demonstrate that for a couple of time zones, each time formatting the date-time using the same formatter I used for parsing, since I gather you tend to like the yyyy-MM-dd HH:mm:ss format.

我总是以 region/city 格式提供时区.这是明确的(与三个字母的缩写相反;例如,PYT可能表示巴拉圭时间或平壤时间).如果时区使用夏令时,它将自动处理夏令时(DST).甚至区域偏移的历史性变化都是内置的.

I always give time zone in the region/city format. This is unambiguous (contrary to three letter abbreviations; for example, PYT may mean Paraguay Time or Pyongyang Time). And it will automatically take care of summer time (DST) in case the time zone uses such. Even historic changes in zone offset are built-in.

要学习使用 java.time ,请参见 Oracle关于日期时间的教程,并在Stack Overflow上搜索相关问题,始终寻找 java.time 答案(使用过时的类有很多旧答案,请跳过那些).网上甚至更多的地方拥有宝贵的资源.您的搜索引擎和分辨好与坏的能力就是您的朋友.

To learn to use java.time, see the Oracle Tutorial on Date Time and search for relevant questions on Stack Overflow, always looking for the java.time answers (there’s a wealth of old answers using the outdated classes, skip those). Even more places on the net hold valuable resources. Your search engine and your ability to distinguish good from poor are your friends.

这篇关于Java设置的时区不默认为gmt + 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆