Java DateFormat parse() doesn't respect the timezone

后端 未结 3 1137
小蘑菇
小蘑菇 2021-01-01 21:01
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
df.         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 21:14

    You're printing the result of calling Date.toString(), which always uses the default time zone. Basically, you shouldn't use Date.toString() for anything other than debugging.

    Don't forget that a Date doesn't have a time zone - it represents an instant in time, measured as milliseconds since the Unix epoch (midnight on January 1st 1970 UTC).

    If you format the date using your formatter again, that should come up with the same answer as before.

    As an aside, I would recommend the use of Joda Time instead of Date/Calendar if you're doing any significant amount of date/time work in Java; it's a much nicer API.

提交回复
热议问题