I am trying to get the current week number with JodaTime.
In France, weeks are defined like this :
Example : The 1st of January 2012 is a Sunday. Hence,
With JodaTime, I found that I can get the week number with the following method DateTime#getWeekOfWeekyear()
.
I thought that by specifying the right TimeZone, I would get a localized result :
DateTime dtFr = new DateTime(2012, 1, 1, 11,11, DateTimeZone.forTimeZone(TimeZone.getTimeZone("Europe/Paris")));
DateTime dtUS = new DateTime(2012, 1, 1, 11,11, DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Arizona")));
LOGGER.info("weekYear (FR) : " + dtFr.weekyear().get());
LOGGER.info("weekOfWeekYear (FR) : " + dtFr.getWeekOfWeekyear());
LOGGER.info("weekYear (US) : " + dtUS.weekyear().get());
LOGGER.info("weekOfWeekYear (US) : " + dtUS.getWeekOfWeekyear());
The output is :
2014-03-05 11:28:08,708 - INFO - c.g.s.u.JodaTest - weekYear (FR) : 2011
2014-03-05 11:28:08,709 - INFO - c.g.s.u.JodaTest - weekOfWeekYear (FR) : 52
2014-03-05 11:28:08,709 - INFO - c.g.s.u.JodaTest - weekYear (US) : 2011
2014-03-05 11:28:08,709 - INFO - c.g.s.u.JodaTest - weekOfWeekYear (US) : 52
I had expected :
Is there something wrong in my code ?
Sad answer to your question for localized week number: JodaTime does not support it, only the ISO-8601 definition of week numbers. I know for many users this is like a show stopper. Here the old java.util.*-stuff is clearly better.
The only way to realize this feature in JodaTime would be to introduce a specialized date-time-field, but it is surely not easy to implement as the project lead himself admitted. This was already noticed in year 2007, but nothing has happened since.
By the way, time zones have nothing to do with the question of localized week numbers so you cannot cure this old Joda problem with any kind of time zone configuration.
I know this question is 3 years old, but with the java.time classes built into Java 8 and later, this problem can now be resolved with an elegant short code, without Joda-Time:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.WeekFields;
public class USWeek {
public static final WeekFields US_WEEK_FIELDS = WeekFields.of(DayOfWeek.SUNDAY, 4);
// equivalent to: public static final WeekFields US_WEEK_FIELDS = WeekFields.SUNDAY_START;
// equivalent to: public static final WeekFields US_WEEK_FIELDS = WeekFields.of(Locale.US);
public static int getWeek(LocalDate date) {
return date.get(US_WEEK_FIELDS.weekOfWeekBasedYear());
}
public static int getYear(LocalDate date) {
return date.get(US_WEEK_FIELDS.weekBasedYear());
}
}
Note: in this code, US weeks definition is hardcoded. The WeekFields
object can also be defined from a Locale
by calling WeekFields.of( Locale ).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With