将IDT / IST中的时间转换为UTC中的unixtime

时间:2017-01-19 10:36:42

标签: java date timezone simpledateformat unix-timestamp

我正在尝试将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而不是05:30:20或04:30:20(IST / IDT)的unixtime

1 个答案:

答案 0 :(得分:3)

如果您希望在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 - 符号“z”将其解释为Israel Standard Time(在我的环境中至少对我有效)。如果您想确定“IST”的正确解释,那么您应该考虑在解析时切换库并设置您对Israel Time的偏好,例如在Java-8中:

DateTimeFormatterBuilder.setZoneText(TextStyle.SHORT, Collections.singleton(ZoneId.of("Asia/Jerusalem")))