也许这是一个附带的要求,因为找到一个行之有效的解决方案是非常棘手的。
我开了个变焦会
“时区”:“欧洲/柏林”,"created_at":"2020-11-20T19:35:22Z",
我想要一个Java,当检查或输出(SimpleDateFormat)时,它看起来像created_at +时区的偏移量。
考虑到我在一个去柏林的不同时区,我尝试过的大多数路线都是根据我无法到达的系统日期进行各种调整。
在经历了很多痛苦之后,我得到了这个方法(为了这篇文章,我变得不那么通用了)。我希望这对某人有帮助,如果有一个不那么麻烦的解决方案,我很想知道:)
发布于 2020-11-20 20:28:47
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级别仍然不符合Java-8,请检查通过desugaring提供的Java 8+ API和如何在安卓项目中使用ThreeTenABP。
使用遗留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中表示日期时间.
发布于 2020-11-20 20:22:52
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", ""));
}https://stackoverflow.com/questions/64936365
复制相似问题