开发者

java Calender/formatter provides wrong date

开发者 https://www.devze.com 2023-02-15 01:50 出处:网络
Somehow I am being reported a issue, in which following code provides date in future. The timezone used is GMT+01:00.

Somehow I am being reported a issue, in which following code provides date in future.

The timezone used is GMT+01:00. The numberOfDays is non negative integer.

The intention of this code is reduce the number of days from current date.

SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yy",Locale.ENGLISH);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -numberOfDays);
Date date = calendar.getTime();
String dateStr= formatter.format(date);
System.out.println("Date : "+dateStr);

I am not able to reproduce this on my machine.

Does the Locale affect the TimeZone?

I tried to correlate to Why does a new SimpleDateFormat object contain calendar with the wrong year?, and Strange problem with timezone, calen开发者_StackOverflow社区dar and SimpleDateFormat but in vain.

Please help me understand and rectify this issue.


Well, two possibilities I can think of off the top of my head:

  • The system date on the client machine is incorrect, so the calendar starts with a date in the future
  • If numberOfDays is negative, it will obviously push the date into the future

The Locale isn't directly related to the time zone - they're independent, although obviously a machine with a French locale is likely to be in a French time zone etc.

Personally I would avoid using Date/Calendar entirely and use Joda Time as a much nicer date and time API, but that wouldn't help with either of the ideas I gave above...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号