How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));
Related
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?
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
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 ...
}
// 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());
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();
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")
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());
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() ;
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)
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
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");
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
I am having issues with the calculation of when the next Last Day of the Month is for a notification which is scheduled to be sent.
Here is my code:
RecurrenceFrequency recurrenceFrequency = notification.getRecurrenceFrequency();
Calendar nextNotifTime = Calendar.getInstance();
This is the line causing issues I believe:
nextNotifTime.add(recurrenceFrequency.getRecurrencePeriod(),
recurrenceFrequency.getRecurrenceOffset());
How can I use the Calendar to properly set the last day of the next month for the notification?
Calendar.getInstance().getActualMaximum(Calendar.DAY_OF_MONTH);
This returns actual maximum for current month. For example it is February of leap year now, so it returns 29 as int.
java.time.temporal.TemporalAdjusters.lastDayOfMonth()
Using the java.time library built into Java 8, you can use the TemporalAdjuster interface. We find an implementation ready for use in the TemporalAdjusters utility class: lastDayOfMonth.
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
LocalDate now = LocalDate.now(); //2015-11-23
LocalDate lastDay = now.with(TemporalAdjusters.lastDayOfMonth()); //2015-11-30
If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like
lastDay.atStartOfDay(); //2015-11-30T00:00
And to get last day as Date object:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
Date lastDayOfMonth = cal.getTime();
You can set the calendar to the first of next month and then subtract a day.
Calendar nextNotifTime = Calendar.getInstance();
nextNotifTime.add(Calendar.MONTH, 1);
nextNotifTime.set(Calendar.DATE, 1);
nextNotifTime.add(Calendar.DATE, -1);
After running this code nextNotifTime will be set to the last day of the current month. Keep in mind if today is the last day of the month the net effect of this code is that the Calendar object remains unchanged.
Following will always give proper results:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, ANY_MONTH);
cal.set(Calendar.YEAR, ANY_YEAR);
cal.set(Calendar.DAY_OF_MONTH, 1);// This is necessary to get proper results
cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
cal.getTime();
You can also use YearMonth.
Like:
YearMonth.of(2019,7).atEndOfMonth()
YearMonth.of(2019,7).atDay(1)
See
https://docs.oracle.com/javase/8/docs/api/java/time/YearMonth.html#atEndOfMonth--
Using the latest java.time library here is the best solution:
LocalDate date = LocalDate.now();
LocalDate endOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
Alternatively, you can do:
LocalDate endOfMonth = date.withDayOfMonth(date.lengthOfMonth());
Look at the getActualMaximum(int field) method of the Calendar object.
If you set your Calendar object to be in the month for which you are seeking the last date, then getActualMaximum(Calendar.DAY_OF_MONTH) will give you the last day.
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse("11/02/2016");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("First Day Of Month : " + calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
System.out.println("Last Day of Month : " + calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
Kotlin date extension implementation using java.util.Calendar
fun Date.toEndOfMonth(): Date {
return Calendar.getInstance().apply {
time = this#toEndOfMonth
}.toEndOfMonth().time
}
fun Calendar.toEndOfMonth(): Calendar {
set(Calendar.DAY_OF_MONTH, getActualMaximum(Calendar.DAY_OF_MONTH))
return this
}
You can call toEndOfMonth function on each Date object like Date().toEndOfMonth()
I want to find the date of the first occurrence of a Sunday before a given date.
e.g. I have a method that excepts current date and lets say the date is today's date Tuesday 02-09-2014 and the method will return the date of the past Sunday 31-08-2014.
Is there any way that I can get it done in Java??
Thanks in advance
With java 8 you can use one of the built-in TemporalAdjusters:
LocalDate today = LocalDate.now();
LocalDate previousSunday = today.with(previous(SUNDAY));
//or if today is a Sunday and you want to return today:
LocalDate previousSunday = today.with(previousOrSame(SUNDAY));
note: assumes static imports:
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.previous;
Try this:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_WEEK, -(cal.get(Calendar.DAY_OF_WEEK) - 1));
System.out.println(cal.getTime());
Something like this will work.
Calendar cal = Calendar.getInstance();
int diff = cal.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
cal.add(Calendar.DAY_OF_MONTH, -diff);
System.out.println(cal.getTime());
Using java.util.Calendar
Substract the difference (in days) between sunday and now:
Calendar c = Calendar.getInstance();
int day = c.get( Calendar.DAY_OF_WEEK );
c.add( Calendar.DAY_OF_WEEK, Calendar.SUNDAY - day);
And you got it.
How to get month from a date in java :
DateFormat inputDF = new SimpleDateFormat("mm/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
This code return day and year but not month.
output :
0 - 30 - 2011
This is because your format is incorrect: you need "MM/dd/yy" for the month, because "mm" is for minutes:
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
Prints 8 - 30 - 2011 (because months are zero-based; demo)
First, you used mm in your date format, which is "minutes" according to the Javadocs. You set the minutes to 9, not the month. It looks like the month defaults to 0 (January).
Use MM (capital 'M's) to parse the month. Then, you will see 8, because in Calendar months start with 0, not 1. Add 1 to get back the desired 9.
The first month of the year in the Gregorian and Julian calendars is
JANUARY which is 0
// MM is month, mm is minutes
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
and later
int month = cal.get(Calendar.MONTH) + 1; // To shift range from 0-11 to 1-12
If you read the SimpleDateFormat javadoc, you'll notice that mm is for minutes. You need MM for month.
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Otherwise the format doesn't read a month field and assumes a value of 0.
Month format should be MM instead of mm
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Time for someone to provide the modern answer. The other answers were good answers when the question was asked in 2013 and are still correct. Today there is no reason why you should struggle with the old, outdated and simultaneously notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API, is so much nicer to work with:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter);
System.out.println(date1);
This prints
2011-09-30
The LocalDate class represents a date without time-of-day, exactly what you need, it matches your requirement much more precisely than the old classes Date and Calendar.
The format pattern strings used with DateTimeFormatter resemble those from SimpleDateFormat, there are a few differences. You may use uppercase MM to require two-digit month (like 09 for September) or a single M to allow the month to be written with one or two digits. Similarly dd or d for day of month. yy denotes two-digit year and is interpreted with base 2000, that is, from 2000 to 2099 inclusive (wouldn’t work for my birthday).
Link: Oracle tutorial Trail: Date Time explaining how to use java.time.
Try like this using MM instead of mm:-
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
The month printed will be 8 as index starts from 0
or try with:-
int month = cal.get(Calendar.MONTH) + 1;
mmis for minutes, use MM while specifying format.
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);// returns month value index starts from 0
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?
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
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 ...
}
// 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());
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();
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")
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());
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() ;
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)
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
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");
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