我想将字符串存储到具有当前时间和日期的 Android 应用程序的数据库(SQLite)中。为此,我正在使用 SimpleDateFormat。不幸的是,它没有显示正确的时间。我尝试了两种选择。
第一个选项(来自 SimpleDateFormat with TimeZone)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z", Locale.getDefault());
sdf.format(new Date());
第二个选项(来自 Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST) SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss'Z'");
sdf2.setTimeZone(TimeZone.getTimeZone("CEST"));
在这两种情况下,时间都是错误的。我的笔记本电脑或手机显示的不是本地时间,但输出时间提前了 2 小时。我该如何改变呢?我想在我的电脑上也显示柏林的当前时间(CEST)。我感谢每一条评论。
最佳答案
使用Europe/Berlin
而不是 CEST
你会得到预期的结果。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
sdf2.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));
System.out.println(sdf2.format(new Date()));
}
}
输出:2020-09-27 18:38:04 +0200
一个忠告:我建议您从过时且容易出错的
java.util
中切换。日期时间 API 和 SimpleDateFormat
到modern java.time
日期时间 API 和相应的格式化 API(包,java.time.format
)。从 了解有关现代日期时间 API 的更多信息Trail: Date Time .如果您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring和 How to use ThreeTenABP in Android Project .使用现代日期时间 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.now(ZoneId.of("Europe/Berlin"));
// Default format
System.out.println(zdt);
// Some custom format
System.out.println(zdt.format(DateTimeFormatter.ofPattern("EEEE dd uuuu hh:mm:ss a z")));
}
}
输出:2020-09-27T18:42:53.620168+02:00[Europe/Berlin]
Sunday 27 2020 06:42:53 pm CEST
现代 API 会提醒您,而旧版 API 可能会发生故障转移:import java.time.ZoneId;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("CEST"));
// ...
}
}
输出:Exception in thread "main" java.time.zone.ZoneRulesException: Unknown time-zone ID: CEST
at java.base/java.time.zone.ZoneRulesProvider.getProvider(ZoneRulesProvider.java:279)
at java.base/java.time.zone.ZoneRulesProvider.getRules(ZoneRulesProvider.java:234)
at java.base/java.time.ZoneRegion.ofId(ZoneRegion.java:120)
at java.base/java.time.ZoneId.of(ZoneId.java:408)
at java.base/java.time.ZoneId.of(ZoneId.java:356)
at Main.main(Main.java:6)
如您所见,在这种情况下会出现异常,而 SimpleDateFormat
会给你不受欢迎的结果,如下所示:import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
sdf2.setTimeZone(TimeZone.getTimeZone("CEST"));
System.out.println(sdf2.format(new Date()));
}
}
输出:2020-09-27 16:47:45 +0000
您可能想知道这个不良结果指的是什么。 答案是 : 当SimpleDateFormat
不了解时区,它会故障转移(默认)到 GMT
(与 UTC
相同)即它忽略了 CEST
并申请GMT
在这种情况下(恕我直言,这不是一个好的功能😊)。
关于java - SimpleDateFormat 显示错误的本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64088810/