0

I want to return the week and year of a date like 2016/06. Therefore I use the following code to try it out:

public static void main(String[] args) throws ParseException {

    DateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
    DateFormat formatWeekAndYear = new SimpleDateFormat("yyyy/ww");

    String articleDate = "31.12.2015 11:26:00";

    long keyDate = format.parse(articleDate).getTime();
    System.out.println("KeyDate: " + keyDate + " = " + format.format(keyDate));

    String formatted = formatWeekAndYear.format(keyDate);
    System.out.println(formatted);
}

I want to return a <Year> / <Week Of Year> string for any input date, e.g. 31.12.2015 11:26:00 (see code).

Now the strange behavior:

I get different results, dependent on which computer I run the Java program!

Here the output on my local PC:

KeyDate: 1451557560000 = 31.12.2015 11:26:00
2015/53

Running exact the same program on a remote machine I get:

KeyDate: 1451557560000 = 31.12.2015 11:26:00
2015/01

Why returns computer A 2015/53 and the other 2015/01. It took me days to find out this difference, can someone give an explanation?

D. Müller
  • 3,336
  • 4
  • 36
  • 84

1 Answers1

2

The reason is quite simple... you are ignoring the locale but the definition of Week of Year is 100% Locale dependent.

you should consider inthis case to create an instance of the SimpleDateFormat with locale ...

The reason why is: the 1st week in USA is not the same as the 1st week in Germany..

consider following piece of code, that explains the different results for the same code with different locale...

Example:

public static void main(String[] args) {

DateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
DateFormat formatWeekAndYear = new SimpleDateFormat("yyyy/ww");
DateFormat formatWeekAndYearGERMANY = new SimpleDateFormat("yyyy/ww", Locale.GERMAN);

String articleDate = "31.12.2015 11:26:00";

long keyDate = 1451557560000L;
System.out.println("KeyDate: " + keyDate + " = " + format.format(keyDate));

System.out.println("in USA:" + formatWeekAndYear.format(keyDate));
System.out.println("aber in Berlin:" + formatWeekAndYearGERMANY.format(keyDate));
}

the output looks like:

KeyDate: 1451557560000 = 31.12.2015 11:26:00

in USA: 2015/01

aber in Berlin: 2015/53

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
  • This is the solution, adding Locale.GERMANY to my DateFormatter solved my issue! Thank you, this saved my day! – D. Müller Aug 09 '16 at 06:23
  • you are willkommen :) – ΦXocę 웃 Пepeúpa ツ Aug 09 '16 at 06:24
  • If you want a [standard ISO 8601 definition of a week](https://en.m.wikipedia.org/wiki/ISO_week_date), use the [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html) class instead of these troublesome old legacy classes. – Basil Bourque Aug 09 '16 at 06:42