How to get start and end date of a year?
Asked Answered
T

17

45

I have to use the Java Date class for this problem (it interfaces with something out of my control).

How do I get the start and end date of a year and then iterate through each date?

Tennant answered 21/2, 2012 at 18:18 Comment(8)
Date is decapricated. Use Calendar instead.Copier
So, Calendar is not an option? @Stas: this is not true. A bunch of deprecated methods doesn't make the whole class deprecated.Tim
@BalusC: "Prior to JDK 1.1, the class Date had two additional functions. It allowed the interpretation of dates as year, month, day, hour, minute, and second values. It also allowed the formatting and parsing of date strings. Unfortunately, the API for these functions was not amenable to internationalization. As of JDK 1.1, the Calendar class should be used to convert between dates and time fields and the DateFormat class should be used to format and parse date strings. The corresponding methods in Date are deprecated."Copier
@Stas: the corresponding methods are deprecated, not the class itself.Tim
@BalusC: Yes, and according to the question, those are the methods that he needs.Copier
@stas: drugs are bad. Don't do them.Leslee
Date and Calendar are both outdated and poorly designed. Use java.time instead.Douma
Consider accepting https://mcmap.net/q/365976/-how-to-get-start-and-end-date-of-a-year. The accepted answer is now deprecated.Impresario
P
122

java.time

Using java.time library built into Java 8 and later. Specifically the LocalDate and TemporalAdjusters classes.

import java.time.LocalDate
import static java.time.temporal.TemporalAdjusters.firstDayOfYear
import static java.time.temporal.TemporalAdjusters.lastDayOfYear

LocalDate now = LocalDate.now(); // 2015-11-23
LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01
LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31

If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

lastDay.atStartOfDay(); // 2015-12-31T00:00
Pneumatometer answered 23/11, 2015 at 8:51 Comment(1)
Good Answer. I suggest always passing the desired/expected time zone to LocalDate.now( ZoneId ) rather than relying implicitly on the JVM’s current default time zone which can change at any moment during runtime. LocalDate.now( ZoneId.of( "America/Montreal" ) ) Likewise, always pass a ZoneId to the atStartOfDay method rather than rely implicitly on JVM default. lastDay.atStartOfDay( ZoneID.of( "America/Montreal" ) )Glandular
H
49
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.DAY_OF_YEAR, 1);    
Date start = cal.getTime();

//set date to last day of 2014
cal.set(Calendar.YEAR, 2014);
cal.set(Calendar.MONTH, 11); // 11 = december
cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve

Date end = cal.getTime();

//Iterate through the two dates 
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
    gcal.add(Calendar.DAY_OF_YEAR, 1);
    //Do Something ...
}
Hypothesis answered 21/2, 2012 at 18:29 Comment(3)
Ahh I didn't realise you could convert between calendar and date!Tennant
You dont convert between them; A Date represents an instant in time, while a Calendar tells you how that instant is represented in a particular system.Leary
This code can be improved with constants such as cal.set(Calendar.MONTH, Calendar.DECEMBER);Licorice
T
7
    // suppose that I have the following variable as input
    int year=2011;
    Calendar calendarStart=Calendar.getInstance();
    calendarStart.set(Calendar.YEAR,year);
    calendarStart.set(Calendar.MONTH,0);
    calendarStart.set(Calendar.DAY_OF_MONTH,1);
    // returning the first date
    Date startDate=calendarStart.getTime();

    Calendar calendarEnd=Calendar.getInstance();
    calendarEnd.set(Calendar.YEAR,year);
    calendarEnd.set(Calendar.MONTH,11);
    calendarEnd.set(Calendar.DAY_OF_MONTH,31);

    // returning the last date
    Date endDate=calendarEnd.getTime();

To iterate, you should use the calendar object and increment the day_of_month variable

Hope that it can help

Trinity answered 21/2, 2012 at 18:29 Comment(1)
Ahh I didn't realise you could convert between calendar and date!Tennant
M
5
 Calendar cal = new GregorianCalendar();
     cal.set(Calendar.DAY_OF_YEAR, 1);
     System.out.println(cal.getTime().toString());
     cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years
     System.out.println(cal.getTime().toString());
Mazer answered 21/2, 2012 at 18:36 Comment(2)
Is this going to work for non-leap years? Or should it be corrected manually?Auxochrome
Remember that some years will have 365 days and others will have 366. That approach shouldn't me used.Testate
L
5

If you are looking for a one-line-expression, I usually use this:

new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01")
Lyublin answered 5/9, 2016 at 10:56 Comment(0)
S
4

An improvement over Srini's answer.
Determine the last date of the year using Calendar.getActualMaximum.

Calendar cal = Calendar.getInstance();

calDate.set(Calendar.DAY_OF_YEAR, 1);
Date yearStartDate = calDate.getTime();

calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR));
Date yearEndDate = calDate.getTime();
Scumble answered 5/5, 2017 at 10:59 Comment(0)
P
2

I assume that you have Date class instance and you need to find first date and last date of the current year in terms of Date class instance. You can use the Calendar class for this. Construct Calendar instance using provided date class instance. Set the MONTH and DAY_OF_MONTH field to 0 and 1 respectively, then use getTime() method which will return Date class instance representing first day of year. You can use same technique to find end of year.

    Date date = new Date();
    System.out.println("date: "+date);
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);

    System.out.println("cal:"+cal.getTime());

    cal.set(Calendar.MONTH, 0);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    System.out.println("cal new: "+cal.getTime());
Prevost answered 21/2, 2012 at 18:29 Comment(0)
T
2

java.time.Year

There is a Year class in java.time.

Examples:

final Year thisYear = Year.of(2024);
System.out.println(thisYear.atDay(1));
System.out.println(thisYear.atDay(thisYear.length()));

Or:

final Year thisYear = Year.of(2024);
System.out.println(thisYear.atMonth(Month.JANUARY).atDay(1));
System.out.println(thisYear.atMonth(Month.DECEMBER).atDay(31));

Or:

final Year thisYear = Year.of(2024);
System.out.println(thisYear.atMonth(Month.JANUARY).atDay(1));
System.out.println(thisYear.atMonth(Month.DECEMBER).atEndOfMonth());

Outputs:

2024-01-01
2024-12-31

To iterate through each date, use LocalDate#datesUntil to create a stream of LocalDate objects.

Year.of(2024).atDay(1)
.datesUntil(
    Year.of(2024).plusYears(1).atDay(1)
)
.forEach( System.out::println ) ;

See that code run at Ideone.com.

2024-01-01
2024-01-02
…
2024-12-30
2024-12-31
Trainee answered 14/11, 2023 at 11:2 Comment(0)
G
1

Update: The Joda-Time library is now in maintenance mode with its team advising migration to the java.time classes. See the correct java.time Answer by Przemek.

Time Zone

The other Answers ignore the crucial issue of time zone.

Joda-Time

Avoid doing date-time work with the notoriously troublesome java.util.Date class. Instead use either Joda-Time or java.time. Convert to j.u.Date objects as needed for interoperability.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ) ;
int year = 2015 ;
DateTime firstOfYear = new DateTime( year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone ) ;
DateTime firstOfNextYear = firstOfYear.plusYears( 1 ) ;
DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays( 1 ) ;

Convert To java.util.Date

Convert to j.u.Date as needed.

java.util.Date d = firstOfYear.toDate() ;
Glandular answered 12/6, 2015 at 8:36 Comment(0)
E
1

This can be done using TemporalAdjusters methods. The following snippet returns the first date and last date of the current year. However, custom input can also work

 LocalDate localDate = LocalDate.now(ZoneId.systemDefault());
    String firstDayOfYear = localDate.with(TemporalAdjusters.firstDayOfYear()).toString();
    String lastDayOfYear = localDate.with(TemporalAdjusters.lastDayOfYear()).toString();
Exfoliation answered 2/8, 2023 at 5:0 Comment(1)
Same solution as in Przemek's answer from 2015 (8 years old) !!Carrot
S
0

You can use Jodatime as shown in this thread Java Joda Time - Implement a Date range iterator

Also, you can use gregorian calendar and move one day at a time, as shown here. I need a cycle which iterates through dates interval

PS. Piece of advice: search it first.

Secretory answered 21/2, 2012 at 18:24 Comment(0)
B
0

You can use the apache commons-lang project which has a DateUtils class.

They provide an iterator which you can give the Date object.

But I highly suggest using the Calendar class as suggested by the other answers.

Baily answered 21/2, 2012 at 18:39 Comment(0)
T
0

First and Last day of Year

import java.util.Calendar
import java.text.SimpleDateFormat

val parsedDateInt = new SimpleDateFormat("yyyy-MM-dd")

val cal2 = Calendar.getInstance()
cal2.add(Calendar.MONTH, -(cal2.get(Calendar.MONTH)))
cal2.set(Calendar.DATE, 1)
val firstDayOfYear = parsedDateInt.format(cal2.getTime)


cal2.add(Calendar.MONTH, (11-(cal2.get(Calendar.MONTH))))
cal2.set(Calendar.DATE, cal2.getActualMaximum(Calendar.DAY_OF_MONTH))
val lastDayOfYear = parsedDateInt.format(cal2.getTime)
Tobar answered 6/9, 2018 at 10:0 Comment(1)
These terrible old legacy classes were supplanted years ago by the modern java.time classes. Suggesting their use in 2018 is poor advice.Glandular
L
0
val instance = Calendar.getInstance()
                instance.add(Calendar.YEAR,-1)

 val prevYear = SimpleDateFormat("yyyy").format(DateTime(instance.timeInMillis).toDate())

val firstDayPreviousYear = DateTime(prevYear.toInt(), 1, 1, 0, 0, 0, 0)

val lastDayPreviousYear = DateTime(prevYear.toInt(), 12, 31, 0, 0, 0, 0)
Laky answered 1/8, 2019 at 3:33 Comment(1)
These terrible date-time classes were supplanted years ago by the java.time classes defined in JSR 310. Suggesting their use in 2019 is poor advice. See modern solution in Answer by Przemek.Glandular
I
-1
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method
we have a get() method to get the specified field of the calendar i.e year

int year=cal.get(Calendar.YEAR);//for example we get 2013 here 

cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30.

Date firstdate=cal.getTime();//here we will get the first day of the year

cal.set(year,11,31);//same way as the above we set the end date of the year

Date lastdate=cal.getTime();//here we will get the last day of the year

System.out.print("the firstdate and lastdate here\n");
Intellectualism answered 7/2, 2013 at 11:48 Comment(1)
Might you explain your code, please? It's not very helpful at the moment.Carleycarli
W
-1
GregorianCalendar gcal = new GregorianCalendar();
gcal.setTime(start);
while (gcal.getTime().before(end)) {
    gcal.add(Calendar.DAY_OF_YEAR, 1);
    //Do Something ...
}

The GregorianCalendar creation here is pointless. In fact, going through Calendar.java source code shows that Calendar.getInstance() already gives a GregorianCalendar instance.

Regards, Nicolas

Warrick answered 3/1, 2014 at 11:16 Comment(0)
H
-2

java.time.YearMonth

How to Get First Date and Last Date For Specific Year and Month.

Here is code using YearMonth Class.

YearMonth is a final class in java.time package, introduced in Java 8.

public static void main(String[] args) {

    int year = 2021;  // you can pass any value of year Like 2020,2021...
    int month = 6;   // you can pass any value of month Like 1,2,3...
    YearMonth yearMonth = YearMonth.of( year, month );  
    LocalDate firstOfMonth = yearMonth.atDay( 1 );
    LocalDate lastOfMonth = yearMonth.atEndOfMonth();

    System.out.println(firstOfMonth);
    System.out.println(lastOfMonth);
}

See this code run live at IdeOne.com.

2021-06-01

2021-06-30

Hepzi answered 15/1, 2021 at 7:6 Comment(3)
It’s a beautiful way of doing what you are doing. The question was about the first and last day of a year.Douma
You are headed in the right direction, but the Question was for first and last of the year, not month. You could revamp this answer to use Year class in conjunction with YearMonth via Year#atMonth: Year.of( 2021 ).atMonth( Month.JANUARY ).atDay( 1 ) and Year.of( 2021 ).atMonth( Month.JANUARY ).atEndOfMonth(). Or use Year#atMonthDay.Glandular
I am late to this thread, but here is an answer which answers the question about first date of the year and last date of the same year Integer theYear = 2022; LocalDate startYM = Year.of(theYear).atMonth(Month.JANUARY).atDay(1); LocalDate endYM = Year.of(theYear).atMonth(Month.DECEMBER).atEndOfMonth();Cleancut

© 2022 - 2024 — McMap. All rights reserved.