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
For startDate and endDate as follows how do I determin the period in Months and days (what is left of it):
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date start = format.parse("2016-11-09T02:00:00.000Z");
Date end = format.parse("2017-09-30T09:00:00.000Z");
As a result I want: 10 Months and 22 Days (end date in)
If you can use Java 8, it is better to use LocalDateTime and Period:
ZonedDateTime dateTime = ZonedDateTime.parse("2016-11-09T02:00:00.000Z");
ZonedDateTime end = ZonedDateTime.parse("2017-09-30T09:00:00.000Z");
System.out.println(Period.between(dateTime.toLocalDate(),end.toLocalDate()));
The result is P10M21D 10 Months and 21 Days
This code should work fine for you. This is done using JODA Time. As you tagged this question also with jodatime so I am sure, you will have required packages for jodatime included in your project.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
SimpleDateFormat format = new SimpleDateFormat(pattern);
Date start = format.parse("2016-11-09T02:00:00.000Z");
Date end = format.parse("2017-09-30T09:00:00.000Z");
LocalDate a = LocalDate.fromDateFields(start);
LocalDate b = LocalDate.fromDateFields(end);
Period p = new Period(a, b);
System.out.println("Months: "+((p.getYears() * 12) + p.getMonths()));
System.out.println("Days: "+(p.getWeeks()*7+ p.getDays()));
However, if you are using Java 8.0 or above, you can stick with solution suggested by #Anton.
I want to find out difference in milliseconds between next occuring 3PM new york time and current time. i.e. if it is 5 pm NY time right now. I should get the difference between 5pm now and 3pm NY time next day. How can I do it in Java ? I am happy using JodaTime also, may you please give an exmaple, how this can be done.
Please help.
Here are three solutions using the most prevalent library choices. They all follow the same pattern, just using the nomenclature of the given libraries.
Joda solution:
DateTime dt = new DateTime(DateTimeZone.forID("US/Eastern"));
DateTime target = dt
.withHourOfDay(15)
.withMinuteOfHour(0)
.withSecondOfMinute(0)
.withMillisOfSecond(0);
if (target.isBefore(dt)) {
target = target.plusDays(1);
}
System.out.println(target.getMillis() - dt.getMillis());
Java 8 solution
Got to love that until() method:
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Eastern"));
ZonedDateTime target2 = zdt
.withHour(15)
.withMinute(0)
.withSecond(0)
.withNano(0);
if (target2.isBefore(zdt)) {
zdt = zdt.plusDays(1);
}
System.out.println(zdt.until(target2, ChronoUnit.MILLIS));
Java <=7 solution
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
Calendar target3 = Calendar.getInstance(TimeZone.getTimeZone("US/Eastern"));
target3.set(Calendar.HOUR_OF_DAY, 15);
target3.set(Calendar.MINUTE, 0);
target3.set(Calendar.SECOND, 0);
target3.set(Calendar.MILLISECOND, 0);
if (target3.before(c)) {
target3.add(Calendar.DATE, 1);
}
System.out.println(target3.getTimeInMillis() - c.getTimeInMillis());
How about this?
Date now = new Date();
Calendar ny3pmCalendar = new GregorianCalendar(TimeZone.getTimeZone("America/New_York"));
ny3pmCalendar.setTime(now);
if(ny3pmCalendar.get(Calendar.HOUR_OF_DAY) >= 15) {
// next day
ny3pmCalendar.add(Calendar.DAY_OF_YEAR, 1);
}
ny3pmCalendar.set(Calendar.HOUR, 15);
ny3pmCalendar.set(Calendar.MINUTE, 0);
ny3pmCalendar.set(Calendar.SECOND, 0);
ny3pmCalendar.set(Calendar.MILLISECOND, 0);
long diff = ny3pmCalendar.getTimeInMillis() - now.getTime();
System.out.println(diff);
try joda DateTime and Period
Date oldDate = new Date();
DateTime old = new DateTime(oldDate);
DateTime now = new DateTime();
Period period = new Period(old, now, PeriodType.yearMonthDayTime());
period.getYears();// give the difference in year
period.getMonths();
period.getDays();
period.getMinutes();
period.getSeconds();
Joda Time - Its having lots of features for date time manipulation
I'm using Joda-Time and trying to find the difference between dates.
Is there something wrong with my code?
Here's my code :
LocalDate startDate = new LocalDate (19990-7-18);
LocalDate endDate = new LocalDate (2013-07-18);
Years Age = Years.yearsBetween(startDate, endDate);
int Age1 = Age.getYears();
String Age2 = new Integer(Age1).toString();
I'm using JOptionPane to view the result, and its telling I got 0 on (age1).
You need to add quotation marks " to your LocalDate definitions to use the constructor that takes a String parameter:
LocalDate startDate = new LocalDate("1999-07-18");
LocalDate endDate = new LocalDate("2013-07-18");
What you have written evaluates to longs, and the two dates constructed will in fact be 0 years apart.
Let's say I have this:
PrintStream out = System.out;
Scanner in = new Scanner(System.in);
out.print("Enter a number ... ");
int n = in.nextInt();
I have a random date, for example, 05/06/2015 (it is not a fixed date, it is random every time). If I want to take the 'year' of the this date, and add whatever 'n' is to this year, how do i do that?
None of the methods in the Date Class are 'int'.
And to add years from an int, 'years' has to be an int as well.
You need to convert the Date to a Calendar.
Calendar c = Calendar.getInstance();
c.setTime(randomDate);
c.add(Calendar.YEAR, n);
newDate = c.getTime();
You can manipulate the Year (or other fields) as a Calendar, then convert it back to a Date.
This question has long deserved a modern answer. And even more so after Add 10 years to current date in Java 8 has been deemed a duplicate of this question.
The other answers were fine answers in 2012. The years have moved on, today I believe that no one should use the now outdated classes Calendar and Date, not to mention SimpleDateFormat. The modern Java date and time API is so much nicer to work with.
Using the example from that duplicate question, first we need
private static final DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss");
With this we can do:
String currentDateString = "2017-09-12 00:00:00";
LocalDateTime dateTime = LocalDateTime.parse(currentDateString, formatter);
dateTime = dateTime.plusYears(10);
String tenYearsAfterString = dateTime.format(formatter);
System.out.println(tenYearsAfterString);
This prints:
2027-09-12 00:00:00
If you don’t need the time of day, I recommend the LocalDate class instead of LocalDateTime since it is exactly a date without time of day.
LocalDate date = dateTime.toLocalDate();
date = date.plusYears(10);
The result is a date of 2027-09-12.
Question: where can I learn to use the modern API?
You may start with the Oracle tutorial. There’s much more material on the net, go search.
Another package for doing this exists in org.apache.commons.lang3.time, DateUtils.
Date date = new Date();
date = DateUtils.addYears(date, int quantity = 1);
The Date class will not help you, but the Calendar class can:
Calendar cal = Calendar.getInstance();
Date f;
...
cal.setTime(f);
cal.add(Calendar.YEAR, n); // Where n is int
f = cal.getTime();
Notice that you still have to assign a value to the f variable. I frequently use SimpleDateFormat to convert strings to dates.
Hope this helps you.
Try java.util.Calendar type.
Calendar cal=Calendar.getInstance();
cal.setTime(yourDate.getTime());
cal.set(Calendar.YEAR,n);
This will add 3 years to the current date and print the year.
System.out.println(LocalDate.now().plusYears(3).getYear());
If you need add one year a any date use the object Calendar.
Calendar dateMoreOneYear = Calendar.getInstance();
dateMoreOneYear.setTime(dateOriginal);
dateMoreOneYear.add(Calendar.DAY_OF_MONTH, 365);
Try like this as well for a just month and year like (June 2019)
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, n); //here n is no.of year you want to increase
SimpleDateFormat format1 = new SimpleDateFormat("MMM YYYY");
System.out.println(cal.getTime());
String formatted = format1.format(cal.getTime());
System.out.println(formatted);
Try this....
String s = new SimpleDateFormat("YYYY").format(new Date(random_date_in_long)); //
int i = Integer.parseInt(s)+n;