将 IDT/IST 中的时间转换为 UTC 中的 unixtime
Convert time in IDT/IST to unixtime in UTC
我正在尝试将 IDT 和 IST 日期解析为 UTC 中的 unixtime
例如:
Thu Sep 10 07:30:20 IDT 2016
对于这个日期,我想获得日期的 unix 时间,但在 04:30:20
的小时内
如果是 IST,我想在同一日期获得 05:30:20 的 unixtime
SimpleDateFormat formatter= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC");
System.out.println(formatter.parse(date).getTime())
我仍然得到 07:30:20 的 unixtime 而不是 05:30:20 或 04:30:20 (IST/IDT)
如果你想在 UTC 中查看格式化结果,那么你需要第二个格式化程序,其可能具有不同的模式和区域设置,并且区域设置为 UTC:
String input1 = "Sat Sep 10 07:30:20 IDT 2016";
String input2 = "Sat Dec 10 07:30:20 IST 2016";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Date d1 = sdf.parse(input1);
Date d2 = sdf.parse(input2);
SimpleDateFormat sdfOut =
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
sdfOut.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("IDT=>UTC: " + sdfOut.format(d1));
System.out.println("IST=>UTC: " + sdfOut.format(d2));
输出:
IDT=>UTC: Sat Sep 10 04:30:20 UTC 2016
IST=>UTC: Sat Dec 10 05:30:20 UTC 2016
解析格式化程序不需要设置特殊区域,因为您的输入包含相关区域信息。
旁注:解析像 IST 这样的时区缩写是危险的,因为该缩写有多种含义。您显然需要以色列时间,但 IST 更经常被解释为印度标准时间。好吧,你很幸运 SimpleDateFormat
-symbol "z" 将其解释为 Israel Standard Time(至少在我的环境中对我有用)。如果您想确定 "IST" 的正确解释,那么您应该考虑切换库并在解析时设置您对以色列时间的偏好,例如 Java-8:
我正在尝试将 IDT 和 IST 日期解析为 UTC 中的 unixtime
例如:
Thu Sep 10 07:30:20 IDT 2016
对于这个日期,我想获得日期的 unix 时间,但在 04:30:20
的小时内
如果是 IST,我想在同一日期获得 05:30:20 的 unixtime
SimpleDateFormat formatter= new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
formatter.setTimeZone(TimeZone.getTimeZone("UTC");
System.out.println(formatter.parse(date).getTime())
我仍然得到 07:30:20 的 unixtime 而不是 05:30:20 或 04:30:20 (IST/IDT)
如果你想在 UTC 中查看格式化结果,那么你需要第二个格式化程序,其可能具有不同的模式和区域设置,并且区域设置为 UTC:
String input1 = "Sat Sep 10 07:30:20 IDT 2016";
String input2 = "Sat Dec 10 07:30:20 IST 2016";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
Date d1 = sdf.parse(input1);
Date d2 = sdf.parse(input2);
SimpleDateFormat sdfOut =
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
sdfOut.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("IDT=>UTC: " + sdfOut.format(d1));
System.out.println("IST=>UTC: " + sdfOut.format(d2));
输出:
IDT=>UTC: Sat Sep 10 04:30:20 UTC 2016
IST=>UTC: Sat Dec 10 05:30:20 UTC 2016
解析格式化程序不需要设置特殊区域,因为您的输入包含相关区域信息。
旁注:解析像 IST 这样的时区缩写是危险的,因为该缩写有多种含义。您显然需要以色列时间,但 IST 更经常被解释为印度标准时间。好吧,你很幸运 SimpleDateFormat
-symbol "z" 将其解释为 Israel Standard Time(至少在我的环境中对我有用)。如果您想确定 "IST" 的正确解释,那么您应该考虑切换库并在解析时设置您对以色列时间的偏好,例如 Java-8: