Next dates using java - java

How can I calculate next dates using Java?
For example, if the user gives me the current date in a field like 2011-02-21, then I want to give back the same day of the month for the next two months: 2011-03-21, 2011-04-21.

Using Joda-Time:
DateTime dt = new DateTime(2005, 3, 26, 0, 0, 0, 0);
Period everyMonth= Period.months(1);
DateTime dt1 = dt.plus(everyMonth);
DateTime dt2 = dt1.plus(everyMonth);
DateTime dt3 = dt2.plus(everyMonth);
DateTime dt4 = dt3.plus(everyMonth);
DateTime dt5 = dt4.plus(everyMonth);
System.out.println(dt.toDate());
System.out.println(dt1.toDate());
System.out.println(dt2.toDate());
System.out.println(dt3.toDate());
System.out.println(dt4.toDate());
System.out.println(dt5.toDate());
OUTPUT
Sat Mar 26 00:00:00 CST 2005
Tue Apr 26 00:00:00 CDT 2005
Thu May 26 00:00:00 CDT 2005
Sun Jun 26 00:00:00 CDT 2005
Tue Jul 26 00:00:00 CDT 2005
Fri Aug 26 00:00:00 CDT 2005

How about using DateTime of YodaTime?
new DateTime().plusDays(nDays)?
See also plusMonths()

Use Calendar.add(...)
Here is the example:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 31);
c.set(Calendar.MONTH, Calendar.DECEMBER);
System.out.println(c.getTime());
c.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(c.getTime());
This prints:
Sat Dec 31 21:25:12 IST 2011
Sun Jan 01 21:25:12 IST 2012
(I just wanted to check that this really gives correct result when the next date is in the next year.)

Using Calendar like #AlexR said, you can use the add(...) method to add a point in the date.
This:
Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 21);
c.set(Calendar.MONTH, Calendar.FEBRUARY);
System.out.println("user entered date:");
System.out.println(c.getTime());
System.out.println();
System.out.println("next five months:");
for (int i = 0; i < 5; i++) {
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
Prints out:
user entered date:
Mon Feb 21 15:56:49 EST 2011
next five months:
Mon Mar 21 15:56:49 EDT 2011
Thu Apr 21 15:56:49 EDT 2011
Sat May 21 15:56:49 EDT 2011
Tue Jun 21 15:56:49 EDT 2011
Thu Jul 21 15:56:49 EDT 2011

Take a look at the Java Calendar, in particular the method add.

http://answers.yahoo.com/question/index?qid=20080613024301AAm7KbP

Related

How do i get a particular day from Jan to Dec

I am new to java and I am trying to get all the 7th day in the year 2009.
I am a bit confused about how to go about it. Below is my code
public class Main {
public static void main(String[] args) {
System.out.println("WELCOME TO MY CALENDER CLASS");
Calendar calendar = Calendar.getInstance();
calendar.set(DAY_OF_MONTH,7);
calendar.set(Calendar.YEAR,2009);
for(int i =1; i <= 12; i++){
calendar.set(DAY_OF_MONTH,i);
System.out.println(calendar.getTime());
}
}
}
Update: This below is my result
Sun Mar 01 23:41:14 GMT 2009
Mon Mar 02 23:41:14 GMT 2009
Tue Mar 03 23:41:14 GMT 2009
Wed Mar 04 23:41:14 GMT 2009
Thu Mar 05 23:41:14 GMT 2009
Fri Mar 06 23:41:14 GMT 2009
Sat Mar 07 23:41:14 GMT 2009
Sun Mar 08 23:41:14 GMT 2009
Mon Mar 09 23:41:14 GMT 2009
Tue Mar 10 23:41:14 GMT 2009
Wed Mar 11 23:41:14 GMT 2009
Thu Mar 12 23:41:14 GMT 2009
OK, assuming you are starting from 1st of January here is a simple example for your cause. I hope Java1.8 code is clear to you.
public static void main(String[] args) {
// create two localdate start of a year instances, one for current year and one for next year, 2009 and 2010 respectively
LocalDate thisYear = LocalDate.of(2009, Month.JANUARY, 1);
LocalDate nextYear = LocalDate.of(2010, Month.JANUARY, 1);
// used only for counting number of every seventh day in a year
int i=0;
// while we are not in the next year, 2010
while (thisYear.isBefore(nextYear)) {
i++;
// print current date
System.out.println(i+" " + thisYear.toString());
// add a week or seven days to our thisYear instance and loop thru again
thisYear = thisYear.plusWeeks(1);
}
}
The problem with your code is that in the for loop you set the day and not the month for the Calendar object.
So change to this:
for(int i = 0; i < 12; i++){
calendar.set(Calendar.MONTH, i);
System.out.println(calendar.getTime());
}
The loop starts from 0 and goes up to 11 because the months are 0 based.
If you can use LocalDate then your code would be much simpler and more efficient:
System.out.println("WELCOME TO MY CALENDER CLASS");
LocalDate date;
for(int i = 1; i <= 12; i++){
date = LocalDate.of(2009, Month.of(i), 7);
System.out.println(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));
}

SimpleDateFormat date and time pattern

9 PM CST 14 NOV 16 or 9:30 PM CST 14 NOV 16
If my string is the date and time above, what should be my date and time pattern that i could use for SimpleDateFormat? Im not sure what should be the pattern if the time could be 9 only or 9:30.
Is this correct?
SimpleDateFormat sdf = new SimpleDateFormat("h:m aaa z d MMM yy");
I tried testing the above code. For sample date 9:30 PM CST 14 NOV 16, it's working. But for 9 PM CST 14 NOV 16, it's throwing an exception:
java.text.ParseException: Unparseable date: "9 PM CST 14 NOV 16"
You could write a method that tries multiple date format patterns:
public static Date parseDate(String dateToParse) {
String[] dateFormats = {"h aaa z d MMM yy", "h:m aaa z d MMM yy"};
for (String dateFormat : dateFormats) {
try {
return new SimpleDateFormat(dateFormat).parse(dateToParse);
}
catch (ParseException e) {
}
}
return null;
}
Then
Date date1 = parseDate("9 PM CST 14 NOV 16");
System.out.println(date1);
Date date2 = parseDate("9:30 PM CST 14 NOV 16");
System.out.println(date2);
outputs
Mon Nov 14 22:00:00 EST 2016
Mon Nov 14 22:30:00 EST 2016

java.util.GregorianCalendar issue with add() when applying DST changes

My requirement is determining the next date based on frequency of schedule.
So if frequency is DAILY and the first date is 25-Oct-2015 23:59:59,
the next duedate should be exactly 24 hours apart ie 26-Oct-2015 23:59:59
Calendar.add(int field, int amount) seems to be taking care of the same
Eg:
DAILY frequency -- calendar.add(Calendar.DATE, 1);
WEEKLY frequency -- calendar.add(Calendar.DATE, 7);
MONTHLY frequency -- calendar.add(Calendar.MONTH, 1);
The following is the code abstract of the same:
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar();
for(int i=0;i<10;i++) {
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.getTime());
}
}
==================================================
Thu Oct 29 17:17:26 IST 2015 -- in all cases diff is 24 hrs
Fri Oct 30 17:17:26 IST 2015
Sat Oct 31 17:17:26 IST 2015
Sun Nov 01 17:17:26 IST 2015
Mon Nov 02 17:17:26 IST 2015
Tue Nov 03 17:17:26 IST 2015
Wed Nov 04 17:17:26 IST 2015
Thu Nov 05 17:17:26 IST 2015
Fri Nov 06 17:17:26 IST 2015
In case of DAILY frequency and server being in Eastern time (EDT), a few anomaly was ocuuring with add()
As of Nov-1, DST settings change the same are reflected in add
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
for(int i=0;i<10;i++) {
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.getTime());
}
}
-------------------------------------
Wed Oct 28 17:18:14 IST 2015
Thu Oct 29 17:18:14 IST 2015
Fri Oct 30 17:18:14 IST 2015
Sat Oct 31 17:18:14 IST 2015
Sun Nov 01 18:18:14 IST 2015 -- here diff is of 24 + 1 hr
Mon Nov 02 18:18:14 IST 2015
Tue Nov 03 18:18:14 IST 2015
Wed Nov 04 18:18:14 IST 2015 -- else everywhere diff is 24 hours
Thu Nov 05 18:18:14 IST 2015
Fri Nov 06 18:18:14 IST 2015
In case by first date is 25-Oct-2015 23:59:59, in this case, the extra 1 hour shift is causing anomaly as after
31-Oct-2015 23:59:59,
the next date is 2-Nov-2015 00:59:59
Further observing the Code, found out that
// The rest of the fields (week, day or AM_PM fields)
// require time zone offset (both GMT and DST) change
// adjustment.
Actually the server is in EDT, where I'm getting following I/O relation.
I merely tried to debug it on my local instance which is in IST.
public static void main(String[] args) {
Calendar calendar = new GregorianCalendar();
for(int i=0;i<10;i++) {
calendar.add(Calendar.DATE, 1);
System.out.println(calendar.getTime());
}
}
Wed Oct 28 08:09:48 EDT 2015
Thu Oct 29 08:09:48 EDT 2015
Fri Oct 30 08:09:48 EDT 2015
Sat Oct 31 08:09:48 EDT 2015
Sun Nov 01 08:09:48 EST 2015
Mon Nov 02 08:09:48 EST 2015
Tue Nov 03 08:09:48 EST 2015
Wed Nov 04 08:09:48 EST 2015
Thu Nov 05 08:09:48 EST 2015
Fri Nov 06 08:09:48 EST 2015
What should be a reliable way of using a library to ensure that my dates generated are in proper sequence.
Try the below code. The below code doesn't simpley add 1 to DAY or MONTH. It adds milliseconds for a day in order to get the proper result.
public static void main(String[] args) {
DateFormat formatter = new SimpleDateFormat("EEE MMM dd hh:mm:ss z yyyy");
Calendar calendar = Calendar.getInstance();
formatter.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
calendar.setTimeInMillis(System.currentTimeMillis());
long time = calendar.getTimeInMillis();
for(int i=0;i<10;i++) {
System.out.println(formatter.format(calendar.getTime()));
time = time + 86400000;
calendar.setTimeInMillis(time);
}
}
Definitely formatting of the date can be changed by changing the line -
new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy");
It gives output -
Di Okt 27 08:15:59 EDT 2015
Mi Okt 28 08:15:59 EDT 2015
Do Okt 29 08:15:59 EDT 2015
Fr Okt 30 08:15:59 EDT 2015
Sa Okt 31 08:15:59 EDT 2015
So Nov 01 07:15:59 EST 2015
Mo Nov 02 07:15:59 EST 2015
Di Nov 03 07:15:59 EST 2015
Mi Nov 04 07:15:59 EST 2015
Do Nov 05 07:15:59 EST 2015
I think the anomaly is because, the daylight is ending for EDT zone on that day(31st October night).
NO such problem is occurring for IST as India do not have daylight saving.

How to convert Sun Oct 25 18:41:35 IST 2015 to Oct 25 2015 in java?

I have to convert the date Sun Oct 25 18:41:35 IST 2015 into Oct 25 2015 in java.
Any one can you please suggest?
Use this
java.util.Date date = new Date("Sun Oct 25 18:41:35 IST 2015");
SimpleDateFormat formatter = new SimpleDateFormat("MMM dd yyyy");
String format = formatter.format(date);
System.out.println(format);

Quartz cron schedule output not as expected

I want to schedule a daily job at 23:59:59 only in weekdays (monday - friday).
i use this cron expression
"59 59 23 ? * MON-FRI",
but the output has tripe value for monday
Wed Aug 29 23:59:59 ICT 2012
Thu Aug 30 23:59:59 ICT 2012
Fri Aug 31 23:59:59 ICT 2012
Mon Sep 03 23:59:59 ICT 2012
Mon Sep 03 23:59:59 ICT 2012
Mon Sep 03 23:59:59 ICT 2012
Tue Sep 04 23:59:59 ICT 2012
Wed Sep 05 23:59:59 ICT 2012
Thu Sep 06 23:59:59 ICT 2012
Fri Sep 07 23:59:59 ICT 2012
is the expression wrong? need help.
i'm getting this output by loop through specific date, here the code
`try {
CronExpression ce = new CronExpression(59 59 23 ? * MON-FRI);
Calendar start = Calendar.getInstance();
start.setTime(new Date());
Calendar end = Calendar.getInstance();
Date endDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy").parse("Fri Sep 29 23:59:59 ICT 2012");
end.setTime(endDate);
for (; !start.after(endDate); start.add(Calendar.DATE, 1)) {
Date current = start.getTime();
System.out.println(ce.getNextValidTimeAfter(current));
}
} catch (ParseException ex) {
Logger.getLogger(HelloJob.class.getName()).log(Level.SEVERE, null, ex);
}
}`
The problem isn't in you rule or in Quartz, it's OK and you may use it.
The problem is in your test code.
for (; !start.after(endDate); start.add(Calendar.DATE, 1)) {
Date current = start.getTime();
System.out.println(ce.getNextValidTimeAfter(current));
}
You're not iterating on valid dates but on all days between startDate and endDate.
The loop content is called for invalid days too and for each of those 2 invalid days the "next valid time" after current date is monday. So you have thrice monday, that's perfectly logic.
Hence your log.

Categories

Resources