Getting incorrect parsed date when using SimpleDateTimeFormatter with time zone

前端 未结 2 1193
夕颜
夕颜 2021-01-27 17:39

I\'ve the following code:

  SimpleDateFormat format = new SimpleDateFormat(\"EEE MMM dd HH:mm:ss z yyyy\");
    String s2 = \"Mon Oct 19 19:52:21 IST 2015\";
            


        
相关标签:
2条回答
  • 2021-01-27 17:53

    Using IST is dangerous as it could stand for Indian or Israel ST. Assuming you meant Indian ST, try this:

        SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        format.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
        String s2 = "Mon Oct 19 19:52:21 IST 2015";
        System.out.println(format.parse(s2));
    

    Also, follow suggestion from @Meno's answer

    0 讨论(0)
  • 2021-01-27 17:56

    The code expression

    System.out.println(format.parse(s2));
    

    always prints your instant/moment (an object of type java.util.Date) in your system timezone which is apparently PDT. You implicitly apply the method toString()on java.util.Date. Use a dedicated formatter like SimpleDateFormat and set the timezone on this formatter to achieve the desired result.

    Finally you need two formatters, one for parsing and one for printing.

    0 讨论(0)
提交回复
热议问题