Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get start and end date of a year?

Tags:

java

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?

like image 467
Pez Cuckow Avatar asked Feb 21 '12 18:02

Pez Cuckow


People also ask

What is start date and end date?

Agreement Starting and Ending Dates. Each agreement must have a Start Date, which can be any date and time, and an End Date, which can be any date and time after the Start Date. The start date determines the date at which the agreement can be active.


2 Answers

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 
like image 189
Przemek Avatar answered Sep 22 '22 01:09

Przemek


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 ... } 
like image 39
aleroot Avatar answered Sep 22 '22 01:09

aleroot