2

我有以下代码:

DateFormat df = new SimpleDateFormat("M/d/yy h:mm a z");
df.setLenient(false);
System.out.println(df.parse("6/29/2012 5:15 PM IST"));

假设我现在将 PC 的时区设置为太平洋时间(PDT 为 UTC-7),这将打印

2012 年 6 月 29 日星期五 08:15:00 PDT

PDT 不是比 IST(印度标准时间)晚 12.5 小时吗?任何其他时区都不会出现此问题 - 我在日期字符串中尝试了 UTC、PKT、MMT 等而不是 IST。Java中是否有两个IST?

PS:实际代码中的日期字符串来自外部来源,所以我不能使用 GMT 偏移量或任何其他时区格式。

4

4 回答 4

10

时区的缩写名称不明确,并且已弃用 Olson 时区名称。以下内容始终如一,因为 parse() 和 getTimezone() 的行为方式可能有所不同。

SimpleDateFormat sdf = new SimpleDateFormat("M/d/yy h:mm a Z");
TimeZone istTimeZone = TimeZone.getTimeZone("Asia/Kolkata");
Date d = new Date();
sdf.setTimeZone(istTimeZone);
String strtime = sdf.format(d);
于 2013-05-28T19:45:23.443 回答
6

对不起,我必须为此写一个答案,但试试这个代码:

public class Test {

    public static void main(String[] args) throws ParseException {
        DF df = new DF("M/d/yy h:mm a z");
        String [][] zs = df.getDateFormatSymbols().getZoneStrings();
        for( String [] z : zs ) {
            System.out.println( Arrays.toString( z ) );
        }
    }

    private static class DF extends SimpleDateFormat {
        @Override
        public DateFormatSymbols getDateFormatSymbols() {
            return super.getDateFormatSymbols();
        }

        public DF(String pattern) {
            super(pattern);
        }
    }

}

您会发现 IST 在列表中出现了多次,而第一个确实是以色列标准时间。

于 2012-06-29T15:59:32.437 回答
4

不是答案,但请参阅下面的输出 + 代码 - 似乎确实parse将 IST 与TimeZone.getTimeZone("IST")...

2012 年6 月 29 日
星期五 16:15:00 BST 2012 年 6 月 29 日星期五 12:45:00 BST 2012 年 6 月 29 日
星期五 12:45:00 BST 2012
*BST = 伦敦

public static void main(String[] args) throws InterruptedException, ParseException {
    DateFormat fmt1 = new SimpleDateFormat("M/d/yy h:mm a Z");
    Date date = fmt1.parse("6/29/2012 5:15 PM IST");
    System.out.println(date);

    DateFormat fmt2 = new SimpleDateFormat("M/d/yy h:mm a");
    fmt2.setTimeZone(TimeZone.getTimeZone("IST"));
    System.out.println(fmt2.parse("6/29/2012 5:15 PM"));

    DateFormat fmt3 = new SimpleDateFormat("M/d/yy h:mm a");
    fmt3.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
    System.out.println(fmt3.parse("6/29/2012 5:15 PM"));
}
于 2012-06-29T16:04:11.953 回答
0

这是因为 IST 将具有多种含义,例如爱尔兰标准时间、以色列标准时间、印度标准时间。

参考:https ://www.timeanddate.com/time/zones/

专门使用 setTimezone() 方法来设置时区。

例如: parser.setTimeZone(TimeZone.getTimeZone("请在此处详细指定时区"));

于 2018-10-10T12:29:39.600 回答