我有一个日期与我的系统的实际时间(我住在西班牙)。我需要将其更改为UTC-1,但无论我写的是"UTC-1“还是"UTC-2",它总是给我相同的时间,我的意思是:
我的系统小时(time_utc):11:00 13/04/2021试用协调世界时1(时间):09:00 13/04/21试用协调世界时2(时间):09:00 13/04/21
我有这样的代码:
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); 为什么它不起作用?有人能帮我吗?非常感谢!
发布于 2021-04-13 17:59:16
你好!
您可以使用java.time (,如果您被允许并愿意这样做的话)以一种非常简单的方式来完成这项工作。
有一些特殊的类表示不同时区中的时间点。其中之一是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);
}
}它输出以下三行:
2021-04-13T11:00Z
2021-04-13T13:00+02:00
2021-04-13T10:00-01:00如您所见,一天中的时间是根据偏移量进行调整的。
如果需要,可以将输出格式化为所需的样式(目前仅使用OffsetDateTime的toString()方法)。
更新
在使用java.time.format.DateTimeFormatter时,您可以通过将模式定义为uuuu-MM-dd HH:mm来实现按需格式化的输出。
只需在上面的示例中添加以下几行:
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));然后,这将输出
2021-04-13 11:00
2021-04-13 13:00
2021-04-13 10:00如果你真的想要为秒和毫秒修正零,那么就像这样创建你的DateTimeFormatter:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:00.000");这将导致类似如下的输出:
2021-04-13 11:00:00.000
2021-04-13 13:00:00.000
2021-04-13 10:00:00.000发布于 2021-04-14 12:21:02
作为对deHaar的好答案的补充:
举个例子:
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));输出:
2021-04-14T03:12:28.272010-01:00Atlantic/Cape_Verde
2021-04-14 03:00:00.000
在1975年前,佛蒙特州/佛蒙特州的偏移量为-02:00。
你的代码出了什么问题?
这就是旧的TimeZone类的行为是多么令人困惑,也是您永远不应该使用它的原因之一:当给定一个它无法识别的时区ID时,它会返回GMT并假装一切正常。UTC-1不是可识别的时区ID。如果引用实时时区没有意义,而您需要从UTC到-01:00的偏移量,您可以使用GMT-1或GMT-01:00。是的,TimeZone将协调世界时称为格林尼治标准时间,尽管严格来说两者并不相同。
https://stackoverflow.com/questions/67072438
复制相似问题