使用 Java SE 8 日期和时间 API
以下代码
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH)
.withZone(ZoneId.of("Africa/Johannesburg"));
ZonedDateTime zdtSource = ZonedDateTime.parse(strSource, fmt);
做同样的事情
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH);
ZonedDateTime zdtSource = LocalDateTime.parse(strSource, fmt)
.atZone(ZoneId.of("Africa/Johannesburg"));
这意味着使用解析器应用时区是一种要求它将日期时间字符串解析为本地日期时间并将时区粘贴到它的方法。
现在您已经了解了这个概念,让我们讨论一下您发布的要求。
我已经从没有时区的系统作为字符串到有时区的字符串
时区和应用时差
原始字符串:“01/27/2021 14:47:29”
目标字符串:“2021-01-27T13:47:29.000+01:00”
问题:目标系统无法更改格式。我需要申请,
它会自动减去正确的小时数,
取决于夏季/冬季时间。所以这不是一个解决方案
减去 -1。
这里有两点需要理解:
- 只有当给定的本地日期时间来自时区偏移为
UTC+02:00 的时区时,才可以将给定的本地日期时间转换为目标日期时间。 Africa/Johannesburg。 following diagram 描述了 Europe/Berlin 的时区
-
ZonedDateTime 旨在根据夏季/冬季时间自动调整日期时间;因此,您无需明确执行任何操作。
说够了;让我们看一些代码!
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String strSource = "01/27/2021 14:47:29";
DateTimeFormatter fmtInput = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm:ss", Locale.ENGLISH);
ZonedDateTime zdtSource = LocalDateTime.parse(strSource, fmtInput)
.atZone(ZoneId.of("Africa/Johannesburg"));
System.out.println(zdtSource);
ZonedDateTime zdtTarget = zdtSource.withZoneSameInstant(ZoneId.of("Europe/Berlin"));
// Default format
System.out.println(zdtTarget);
// Custom format
DateTimeFormatter fmtOutput = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ENGLISH);
System.out.println(zdtTarget.format(fmtOutput));
}
}
输出:
2021-01-27T14:47:29+02:00[Africa/Johannesburg]
2021-01-27T13:47:29+01:00[Europe/Berlin]
2021-01-27T13:47:29.000+01:00
通过Trail: Date Time了解更多关于modern date-time API的信息。
使用 Joda-Time API
注意:在Home Page of Joda-Time查看以下通知
Joda-Time 是 Java 的事实上的标准日期和时间库
在 Java SE 8 之前。现在要求用户迁移到 java.time
(JSR-310)。
但是,为了完整起见,我使用 Joda-time API 编写了以下代码:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
String strSource = "01/27/2021 14:47:29";
DateTimeFormatter fmtInput = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss")
.withZone(DateTimeZone.forID("Africa/Johannesburg"));
DateTime dtSource = fmtInput.parseDateTime(strSource);
System.out.println(dtSource);
DateTime dtTarget = dtSource.withZone(DateTimeZone.forID("Europe/Berlin"));
System.out.println(dtTarget);
}
}
输出:
2021-01-27T14:47:29.000+02:00
2021-01-27T13:47:29.000+01:00