简体   繁体   English

尝试将时间/日期更改为 UTC-1 时出错

[英]Error when I try to change my time/date to UTC-1

I have a Date with the actual time of my system (I live in Spain).我有一个日期与我的系统的实际时间(我住在西班牙)。 I need to change it to UTC-1, but it doesn't matter if I write "UTC-1" or "UTC-2", it always gives me the same time less 2 hours, I mean:我需要将其更改为 UTC-1,但无论我写“UTC-1”还是“UTC-2”,它总是给我相同的时间少于 2 小时,我的意思是:

My system hour (time_utc): 11:00 13/04/2021 Try UTC-1 (time): 09:00 13/04/21 Try UTC-2 (time): 09:00 13/04/21我的系统时间(time_utc):11:00 13/04/2021 尝试 UTC-1(时间):09:00 13/04/21 尝试 UTC-2(时间):09:00 13/04/21

I have this code:我有这个代码:

    Date time_utc = new Date();
    DateFormat convertidor = new SimpleDateFormat("yyyy-MM-dd HH:00:00.000");    
    
    convertidor.setTimeZone(TimeZone.getTimeZone("UTC-1"));     

    time = convertidor.format(time_utc);    

Why it doesn't work?为什么它不起作用? Can anyone helps me?任何人都可以帮助我吗? Thanks a lot!非常感谢!

¡Hola!你好!

You can do that in a pretty short way using java.time ( if you are allowed and willing to do so ).您可以使用java.time以非常短的方式执行此操作(如果您被允许并愿意这样做)。

There are special classes that represent a moment in time in different time zones of offsets.有一些特殊的类代表不同时区偏移量中的某个时刻。 One of them is an OffsetDateTime , see this example:其中之一是OffsetDateTime ,请参见此示例:

public class Main {

    public static void main(String[] args) {
        // create one of your example date times in UTC
        OffsetDateTime utcOdt = OffsetDateTime.of(2021, 4, 13, 11, 0, 0, 0, ZoneOffset.UTC);
        // and print it
        System.out.println(utcOdt);
        /*
         * then create another OffsetDateTime 
         * representing the very same instant in a different offset
         */
        OffsetDateTime utcPlusTwoOdt = utcOdt.withOffsetSameInstant(ZoneOffset.ofHours(2));
        // and print it
        System.out.println(utcPlusTwoOdt);
        // do that again to see "the other side" of UTC (minus one hour)
        OffsetDateTime utcMinusOneOdt = utcOdt.withOffsetSameInstant(ZoneOffset.ofHours(-1));
        // and print that, too.
        System.out.println(utcMinusOneOdt);
    }
}

It outputs the following three lines:它输出以下三行:

2021-04-13T11:00Z
2021-04-13T13:00+02:00
2021-04-13T10:00-01:00

As you can see, the time of day is adjusted according to the offset.如您所见,一天中的时间根据偏移量进行调整。

The output could be formatted in your desired style if needed (this currently just uses the toString() method of OffsetDateTime ).如果需要,可以将 output 格式化为您想要的样式(目前仅使用OffsetDateTimetoString()方法)。

UPDATE更新

You can achieve the output formatted as desired by defining the pattern as uuuu-MM-dd HH:mm when using a java.time.format.DateTimeFormatter .使用 java.time.format.DateTimeFormatter 时,您可以通过将模式定义为uuuu-MM-dd HH:mm来实现按需要格式化的java.time.format.DateTimeFormatter
Just add the following lines to the example above:只需将以下行添加到上面的示例中:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm");

System.out.println(utcOdt.format(dtf));
System.out.println(utcPlusTwoOdt.format(dtf));
System.out.println(utcMinusOneOdt.format(dtf));

This would then output这将是 output

2021-04-13 11:00
2021-04-13 13:00
2021-04-13 10:00

And if you really want fix zeros for seconds and millis, then create your DateTimeFormatter like this:如果你真的想修复秒和毫秒的零,然后像这样创建你的DateTimeFormatter

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:00.000");

which will cause output like this:这将导致 output 像这样:

2021-04-13 11:00:00.000
2021-04-13 13:00:00.000
2021-04-13 10:00:00.000

As a supplement to the good answer by deHaar:作为 deHaar 良好答案的补充:

  1. As Matt Johnson-Pint already asked, do you need to convert to a different time zone?正如 Matt Johnson-Pint 已经问过的那样,您是否需要转换到不同的时区? This would be the most typical.这将是最典型的。 If so, use that time zone, not just a UTC offset of -1.如果是这样,请使用该时区,而不仅仅是 -1 的 UTC 偏移量。 By all probability that time zone has used other offsets in the past and may well do so in the future.很可能时区过去使用过其他偏移量,并且将来很可能会这样做。 So -01:00 isn't safe.所以 -01:00 不安全。 A real time zone ID like Atlantic/Cape_Verde is safer.像 Atlantic/Cape_Verde 这样的实时区域 ID 更安全。
  2. You don't need to go through the current time in your own time zone and convert.您不需要 go 通过您自己时区的当前时间并进行转换。 java.time can directly give you the current time in another time zone or at a specific UTC offset. java.time 可以直接为您提供另一个时区或特定 UTC 偏移量的当前时间。
  3. java.time can also truncate a time to whole hours. java.time 也可以将时间截断为整小时。

So for example:例如:

    DateTimeFormatter formatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS");
    
    ZoneId zone = ZoneId.of("Atlantic/Cape_Verde");
    ZonedDateTime nowInCaboVerde = ZonedDateTime.now(zone);
    
    System.out.println(nowInCaboVerde);
    System.out.println(nowInCaboVerde.truncatedTo(ChronoUnit.HOURS)
            .format(formatter));

Output: Output:

 2021-04-14T03:12:28.272010-01:00[Atlantic/Cape_Verde] 2021-04-14 03:00:00.000

PS Cabo Verde/Cape Verde was at offset -02:00 until 1975. PS Cabo Verde/Cape Verde 在偏移量 -02:00 直到 1975 年。

What went wrong in your code?你的代码出了什么问题?

This is how confusingly the old TimeZone class behaves and one of the reasons why you should never use it: When given a time zone ID that it does not recognize, it returns GMT and pretends all is well.这就是旧的TimeZone class 的行为方式令人困惑,也是您永远不应使用它的原因之一:当给定一个它无法识别的时区 ID 时,它会返回 GMT 并假装一切正常。 UTC-1 is not a recognized time zone ID. UTC-1不是公认的时区 ID。 In case it didn't make sense to refer to a real time zone and you needed the offset -01:00 from UTC, you might have used GMT-1 or GMT-01:00 .如果引用实时时区没有意义,并且您需要从 UTC 偏移 -01:00,您可能使用了GMT-1GMT-01:00 Yes, TimeZone refers to UTC as GMT even though they are not strictly speaking the same.是的, TimeZone将 UTC 称为 GMT,即使它们在严格意义上并不相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 java中的Date()命令为什么要花时间?我的系统显示utc,我也想要utc时间? - Date() command in java take est time why?My system shows utc and i also want utc time? 当我尝试在连接时进行设置时,将mysql中的Datetime和时间戳从默认时区转换为Java中的UTC无法正常工作 - Convert Datetime and timestamp in mysql from default timezone to UTC in Java is not working when I try to set it at time of connection 当我尝试模拟我的应用程序时出错 - Error when I try to simulate my app 当我尝试更改类名称时出错 - Error when I try to change the class name 从 UTC 时间戳转换时,为什么我总是收到错误的日期/时间? - Why do I keep getting the wrong date/time when converting from a UTC timestamp? UTC 时间自动添加到我的日期变量中 - UTC time is being automatically added in my date variable 格式 UTC 日期时间 - Format UTC Date Time 通过SimpleDateFormat将UTC字符串解析为Date时发生不可解析的日期错误 - Unparseable Date Error when parsing UTC string through SimpleDateFormat to Date 如何在 Java 中获取 UTC 或 GMT 的当前日期和时间? - How can I get the current date and time in UTC or GMT in Java? 如何将当前UTC时间上传到“解析日期”列? - How can I upload current UTC time to Parse date column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM