Dumped in Coldfusion

Monday, December 31, 2007

Week numbers in SimpleDateFormat

It seems that if you use week numbers in formats in java, then you can get stuffed, as there is no way to find out the year that corresponds to the week number that you're looking for.

Today is the 31st December 2007, which is week 1 of 2008. Java correctly says that the week is week 1, and that the year is 2007. Unfortunately this is a little ambiguous, and NOT USEFUL for writing logs.


public static void main(String[] args) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);

DateFormat output = new SimpleDateFormat("yyyy-ww", Locale.ENGLISH);

final Date firstDay = format.parse("2007-01-01");
final Date lastDay = format.parse("2007-12-31");

System.out.println("First: " + output.format(firstDay) + " - " + format.format(firstDay));
System.out.println("Last : " + output.format(lastDay) + " - " + format.format(lastDay));
}

Generates the output

First: 2007-01 - 2007-01-01
Last : 2007-01 - 2007-12-31


If you are using strftime in C etc., then you can use %G for the year, but if you're in java, then you're a bit stuffed.


%G The ISO 8601 year with century as a decimal number. The 4-digit
year corresponding to the ISO week number (see %V). This has
the same format and value as %y, except that if the ISO week
number belongs to the previous or next year, that year is used
instead. (TZ)


Good job I picked today to look at log file naming.

It seems that it isn't possible to make a tomcat valve rotate to a new log weekly. I guess we'll have to go with daily or monthly.

Update: Sun have bugs open for this, 4267450 opened in 1999 and 4808661 a request for 1.6, and many others.

0 Comments:

Post a Comment

<< Home