gpt4 book ai didi

java - 如何使用 Java 将字符串日期和字符串时间组合成单个即时日期时间?

转载 作者:行者123 更新时间:2023-11-30 05:18:00 25 4
gpt4 key购买 nike

我想将字符串日期(“19801115”)和字符串时间(“1530”)组合成一个即时日期时间。

例如:有两个字符串变量:

String applicationDate = "19801115";
String applicationTime = "1530";

并将它们组合成applicationDateTime (即时类型,例如:“1980-11-15T15:30:00Z”)。我该如何实现这一目标?谢谢。

最佳答案

String dateString = "19801115";
String timeString = "1530";

Date date = null;
try {
date = new SimpleDateFormat("yyyyMMddhhmm").parse(dateString + timeString);
} catch (ParseException e) {
e.printStackTrace();
}
Instant reqInstant = date.toInstant();
System.out.println(reqInstant); // time here depends on your local settings, may differ from 15:30

// this way you adjust an Instant to a time zone you need
ZonedDateTime zdt = ZonedDateTime.ofInstant(reqInstant, ZoneId.systemDefault() /*<- needed time zone here*/);
System.out.println(zdt.toInstant()/*returns an Instant*/);

此外,与 DateTimeFormatter 具有类似的功能:

    String dateString = "19801115";
String timeString = "1530";

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.appendPattern("yyyyMMddHHmm")
.toFormatter()
.withZone(ZoneId.systemDefault() /*<- needed time zone here*/);
ZonedDateTime zdtOriginal = ZonedDateTime.parse(dateString + timeString, dtf);

System.out.println(zdtOriginal.toInstant()/*returns an Instant*/);

// this way you adjust an Instant to a time zone you need
ZonedDateTime zdt = zdtOriginal.withZoneSameLocal(ZoneId.of("GMT") /*<- needed time zone here*/);
System.out.println(zdt.toInstant()/*returns an Instant*/);

关于java - 如何使用 Java 将字符串日期和字符串时间组合成单个即时日期时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60073135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com