也许这是一个附加要求,因为找到一个有效的解决方案真的很难。。
我有一个缩放会议,有
"时区":"欧洲/柏林"created_at":"2020-11-20T19:35:22Z";,
我想要一个Java日期,当检查或输出(SimpleDateFormat(时,它看起来像created_at+时区的偏移量。
考虑到我所在的时区与柏林不同,我尝试的大多数路线都是根据我无法绕过的系统日期进行某种调整。
在经历了很多痛苦之后,我最终采用了这种方法(为了这篇文章,减少了通用性(。我希望这能帮助到一些人,如果有一个不那么棘手的解决方案,我很想知道:(
java.util
的日期时间API及其格式API、SimpleDateFormat
已过时且错误。我建议您应该完全停止使用它们,并切换到现代的日期时间API。
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.parse("2020-11-20T19:35:22Z");
System.out.println(zdt);
ZonedDateTime zdtAtBerlin = zdt.withZoneSameInstant(ZoneId.of("Europe/Berlin"));
System.out.println(zdtAtBerlin);
// Custom format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss'created_at'XXX");
System.out.println(formatter.format(zdtAtBerlin));
}
}
输出:
2020-11-20T19:35:22Z
2020-11-20T20:35:22+01:00[Europe/Berlin]
2020-11-20T20:35:22created_at+01:00
有关现代日期时间API的更多信息,请访问跟踪:日期时间。如果您正在为Android项目工作,并且您的Android API级别仍然不符合Java-8,请检查通过desugaring和如何在Android项目中使用ThreeTenABP提供的Java 8+API。
使用传统API:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) throws ParseException {
String dateTimeStr = "2020-11-20T19:35:22Z";
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
Date date = sdf.parse(dateTimeStr);
System.out.println(sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(sdf.format(date));
// Some other format
DateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'created_at'XXX");
sdf2.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(sdf2.format(date));
}
}
输出:
2020-11-20T19:35:22Z
2020-11-20T20:35:22+01
2020-11-20T20:35:22created_at+01:00
请注意,不应使用该格式对'Z'
进行硬编码。这个'Z'
代表Zulu
并且表示UTC
中的日期时间。
public static Date adjustDateTimeZone(String created_at, String timezone) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date = dateFormat.parse(created_at); //parse the date provided by Zoom
Instant nowUtc = Instant.parse(Constants.dateFormat.format(date)); //Don't create using date.getMillis(). Because there are some weird adjustments that happen.
ZoneId timezoneId = ZoneId.of(timezone);
ZonedDateTime correctedDate = ZonedDateTime.ofInstant(nowUtc, timezoneId);
//An example online showed using ZonedDateTime, and DateFormatter, but it did weird ass adjustments as well, which did not correspond to the 'toString()' output,
// which was correct.
//Therefor I grabbed the twoString() output and created a date from that.
return new SimpleDateFormat("yyyy-MM-ddHH:mm:ss").parse(correctedDate.toString().substring(0, 19).replaceAll("T", ""));
}