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?
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?
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
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 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 ...
}
cal.set(Calendar.MONTH, Calendar.DECEMBER);
–
Licorice // 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
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());
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")
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();
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());
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
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.
The other Answers ignore the crucial issue of time zone.
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 ) ;
java.util.Date
Convert to j.u.Date as needed.
java.util.Date d = firstOfYear.toDate() ;
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();
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.
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.
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)
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)
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");
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
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
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 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.
Calendar
is not an option? @Stas: this is not true. A bunch of deprecated methods doesn't make the whole class deprecated. – TimDate
andCalendar
are both outdated and poorly designed. Use java.time instead. – Douma