In the standard ISO8601 week algorithm, the first week of the year is that in which at least 4 days are in the year. As a result of this definition, day 1 of the first week may be in the previous year. The weekyear allows you to query the effective year for that day. This example uses joda time and java 8 date time API to demonstrate how to get the first day in current year and the first day of the prior year.
Java 8 Date and Time API @Test
public void first_day_in_year_current_year_java8 () {
LocalDate date = LocalDate . of ( 2014 , Month . FEBRUARY , 01 );
LocalDate firstDayOfYear = date . with ( TemporalAdjusters . firstDayOfYear ());
assertEquals ( 1 , firstDayOfYear . getDayOfMonth ());
}
Joda Time First day in current year @Test
public void first_day_in_year_current_year () {
DateTime dateTime = new DateTime ( 2012 , 1 , 1 , 0 , 0 , 0 , 0 );
DateTime firstDayOfTheFirstWeek = dateTime
. withWeekyear ( dateTime . getYear ()). withWeekOfWeekyear ( 1 )
. withDayOfWeek ( 1 );
logger . info ( firstDayOfTheFirstWeek );
assertEquals ( 2012 , firstDayOfTheFirstWeek . getYear ());
assertEquals ( 1 , firstDayOfTheFirstWeek . getMonthOfYear ());
assertEquals ( 2 , firstDayOfTheFirstWeek . getDayOfMonth ());
}
Output
2012-01-02T00:00:00.000-06:00
First day in prior year @Test
public void first_day_in_year_prior_year () {
DateTime dateTime = new DateTime ( 2013 , 1 , 1 , 0 , 0 , 0 , 0 );
DateTime firstDayOfTheFirstWeek = dateTime
. withWeekyear ( dateTime . getYear ()). withWeekOfWeekyear ( 1 )
. withDayOfWeek ( 1 );
logger . info ( firstDayOfTheFirstWeek );
assertEquals ( 2012 , firstDayOfTheFirstWeek . getYear ());
assertEquals ( 12 , firstDayOfTheFirstWeek . getMonthOfYear ());
assertEquals ( 31 , firstDayOfTheFirstWeek . getDayOfMonth ());
}
Output
2012-12-31T00:00:00.000-06:00
First day of year posted by Justin Musgrove on 02 February 2014
Tagged: java and java-date
Share on: Facebook Google+
All the code on this page is available on github:
FirstDayInYear.java