Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug in Java.Calendar in Linux? Year not updated

I've got something strange happening in a server running Linux, while a windows machine performing the same code behaves normally.

It is happening with the following code:

    public static final SimpleDateFormat sqlDateFormat = new SimpleDateFormat("Y-M-d");

    Calendar cal = Calendar.getInstance();
    String now = sqlDateFormat.format(cal.getTime());
    System.out.println(now);
    cal.add(Calendar.DAY_OF_MONTH, -4);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    String trsh = sqlDateFormat.format(cal.getTime());
    System.out.println(trsh);

The output on the windows machine running:

    java version "1.7.0_07"
    Java(TM) SE Runtime Environment (build 1.7.0_07-b11)
    Java HotSpot(TM) 64-Bit Server VM (build 23.3-b01, mixed mode)

    Output:
    2014-01-02
    2013-12-29

The above is matching the expected result.

The output on the Linux machine running:

    java version "1.8.0-ea"
    Java(TM) SE Runtime Environment (build 1.8.0-ea-b108)
    Java HotSpot(TM) 64-Bit Server VM (build 25.0-b50, mixed mode)

    Output:
    2014-01-02
    2014-12-29

This is odd isn't it? Any nice workarounds?

like image 357
Bas Goossen Avatar asked Jan 02 '14 13:01

Bas Goossen


2 Answers

Maybe you have constructed your format object with pattern symbol Y instead of y. Y stands for year of weekdate, not the normal iso calendar year. It is locale-dependent, especially dependent on when the week starts. So the locale settings on your windows machine and the linux server might be different. Remember that java.util.Calendar IS dependent on locale, too.

Try new SimpleDateFormat("yyyy-MM-dd");

like image 122
Meno Hochschild Avatar answered Nov 18 '22 10:11

Meno Hochschild


You have a wrong format for a year in a SimpleDateFormat. You should be using y instead of Y.

like image 5
user987339 Avatar answered Nov 18 '22 12:11

user987339