calculate Third monday of every three month in java? - java

LocalDate date1 = new LocalDate(2015, 3, 22);
LocalDate date2 = new LocalDate(2015, 9, 30);
PeriodType monthDay = PeriodType.yearMonthDay().withYearsRemoved();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
int days = difference.getDays();
int alertMonth = 2;
int intervalLoop = date2.getMonthOfYear() / alertMonth ;
for(int i=date1.getMonthOfYear();i<date2.getMonthOfYear();i++){
int intervalTime = i * alertMonth;
if(intervalTime >13){
return;
}else{
LocalDate d = getNDayOfMonth( DateTimeConstants.WEDNESDAY, 2, i, 2015);
System.out.println("month----> "+i+" "+d);

This code may help..
DateTime urDate = DateTime(date); //Your Date time
DateTime afterThreeMonths = urDate.plusMonths(6); //Add 3 months to your Date
afterThreeMonths.withDayOfWeek(DateTimeConstants.MONDAY); //Find next monday
afterThreeMonths.plusWeeks(2); //Add two more weeks to the first monday.
NB: I never run this code. Try and find it out urself.

Related

How can I create a calculation to get the age of a person from two dates?

I am trying to make a method that will calculate the age of a person. I want the calculation to be done under the second public static int getAge. If the person is born after the current date i want it to print out error -1.
How do I compare the two SimpleDate values dateBd and dateRef in order to get an int value for age?
public static SimpleDate today() {
Calendar todayCal = Calendar.getInstance();
SimpleDate todayDate = new SimpleDate();
todayDate.setDate(todayCal.get(Calendar.MONTH) + 1,
todayCal.get(Calendar.DATE),
todayCal.get(Calendar.YEAR));
return todayDate;
public static int getAge(SimpleDate dateBd) {
int age;
SimpleDate dateToday = today();
age = getAge(dateBd, dateToday);
return age;
public static int getAge(SimpleDate dateBd, SimpleDate dateRef) {
if(getAge(dateBd)>getAge(dateRef)){
system.out.println("error");
}
return -1;
What is SimpleDate ? Anyway here something to get you started
import java.util.GregorianCalendar;
import java.util.Calendar;
public class CalcAge {
public static void main(String [] args) {
// remember ... months are 0-based : jan=0 feb=1 ...
System.out.println
("1962-11-11 : " + age(1962,10,11));
System.out.println
("1999-12-03 : " + age(1999,11,3));
}
private static int age(int y, int m, int d) {
Calendar cal = new GregorianCalendar(y, m, d);
Calendar now = new GregorianCalendar();
int res = now.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
if((cal.get(Calendar.MONTH) > now.get(Calendar.MONTH))
|| (cal.get(Calendar.MONTH) == now.get(Calendar.MONTH)
&& cal.get(Calendar.DAY_OF_MONTH) > now.get(Calendar.DAY_OF_MONTH)))
{
res--;
}
return res;
}
}
Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.
Instead, save yourself (alot) of time and use a dedicated library
Java 8
LocalDate start = LocalDate.of(1972, Month.MARCH, 8);
LocalDate end = LocalDate.now();
long years = ChronoUnit.YEARS.between(start, end);
System.out.println(years);
Which outputs 43
JodaTime
DateTime startDate = new DateTime(1972, DateTimeConstants.MARCH, 8, 0, 0);
DateTime endDate = new DateTime();
Years y = Years.yearsBetween(startDate, endDate);
int years = y.getYears();
System.out.println(years );
Which outputs 43
You can even use a Period to gain more granuarlity...
Period period = new Period(startDate, endDate);
PeriodFormatter hms = new PeriodFormatterBuilder()
.printZeroAlways()
.appendYears()
.appendSeparator(" years, ")
.appendMonths()
.appendSeparator(" months, ")
.appendDays()
.appendLiteral(" days")
.toFormatter();
String result = hms.print(period);
System.out.println(result);
Which prints 43 years, 1 months, 5 days

About days between two dates [duplicate]

This question already has answers here:
Java, Calculate the number of days between two dates [duplicate]
(10 answers)
Closed 7 years ago.
I have noted error in bellow code when trying calculate days between two dates. There isn't right with month February,
Here is code,
public class NewClass {
public int numberOfDays(String fromDate,String toDate)
{
java.util.Calendar cal1 = new java.util.GregorianCalendar();
java.util.Calendar cal2 = new java.util.GregorianCalendar();
StringBuffer sBuffer = new StringBuffer(fromDate);
String yearFrom = sBuffer.substring(6,10);
String monFrom = sBuffer.substring(0,2);
String ddFrom = sBuffer.substring(3,5);
int intYearFrom = Integer.parseInt(yearFrom);
int intMonFrom = Integer.parseInt(monFrom);
int intDdFrom = Integer.parseInt(ddFrom);
cal1.set(intYearFrom, intMonFrom, intDdFrom);
StringBuffer sBuffer1 = new StringBuffer(toDate);
String yearTo = sBuffer1.substring(6,10);
String monTo = sBuffer1.substring(0,2);
String ddTo = sBuffer1.substring(3,5);
int intYearTo = Integer.parseInt(yearTo);
int intMonTo = Integer.parseInt(monTo);
int intDdTo = Integer.parseInt(ddTo);
cal2.set(intYearTo, intMonTo, intDdTo);
int days = daysBetween(cal1.getTime(),cal2.getTime());
return days;
}
public int daysBetween(Date d1, Date d2)
{
return (int)( (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24));
}
public static void main(String[] args) throws ParseException {
String s1 = "02-28-2015";
String s2 = "03-01-2015";
int num=numberOfDays(s1, s2);
System.out.println(num);
}
}
If we gives above dates for varialbe s1 and s2, result is 4. But answer is wrong
because 2015 February has only 28 days.
I think problem is this function part (1000 * 60 * 60 * 24)
If anyone knows what to do with this, please update this code or give me some help!!!
Don't ever try and use the millisecond difference between two times to calculate the differences, there are just to many idiosyncrasies with date/time calculations which can cause all sorts of erroneous errors.
Instead, save yourself (alot) of time and use a dedicated library
Java 8
LocalDate start = LocalDate.of(2015, Month.JANUARY, 1);
LocalDate end = LocalDate.now();
long days = ChronoUnit.DAYS.between(start, end);
System.out.println(days);
Which outputs 69
JodaTime
DateTime startDate = new DateTime(2015, DateTimeConstants.JANUARY, 1, 0, 0);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(days);
Which outputs 69

How to get/compute total number of months using JDateChooser

I'm new to Java
How do I get the total number of months between two (2) jdatechooser? I've search already about this but the date was set to the code, In my case I want to put the dates via JDateChooser.
I can do this through this code but if the year change I was not able to compute the total number of months I want to do this without using JodaTime.
Here is my code
public void month(){
int TotalMonth;
Calendar toDate;
Calendar fromDate;
int increment;
Date dt1 = date1.getDate(); //datechooser 1
Date dt2 = date2.getDate(); //datechooser 2
fromDate = Calendar.getInstance();
toDate = Calendar.getInstance();
if(dt1.after(dt2))
{
fromDate.setTime(dt2);
toDate.setTime(dt1);
}
else
{
fromDate.setTime(dt1);
toDate.setTime(dt2);
}
increment = 0;
TotalMonth = toDate.get(Calendar.MONTH) - (fromDate.get(Calendar.MONTH + increment));
jLabel2.setText(Integer.toString(age));
}
JodaTime is simpler, however...
You need to loop from the start time to the end, incrementing the MONTH field on each loop while the date remains before the end time...
For example...
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar cal1 = Calendar.getInstance();
cal1.setTime(sdf.parse("08/03/1972"));
Calendar cal2 = Calendar.getInstance();
cal2.setTime(sdf.parse("08/03/2014"));
// Yes, you can use cal1, but I you might want
// to preserve it for other reasons...
Calendar cal3 = Calendar.getInstance();
cal3.setTime(cal1.getTime());
int months = 0;
while (cal3.before(cal2)) {
cal3.add(Calendar.MONTH, 1);
months++;
}
System.out.println("Months = " + months);
} catch (ParseException exp) {
exp.printStackTrace();
}
Prints out Months = 505.
If you change cal2 to 08/04/1972, it will print Months = 1

Find all previous Tuesdays in a given range?

What I need to do in my Android project is to find all the previous Tuesdays for the last three months and put them into a String Array. It appears that neither the Calendar Class nor SimpleDateFormat would work for this.
So for example, today is Tuesday, so it would start today and I'd need to return 2013_8_13, and next in the array would be 2013_8_6, then 2013_7_30, and so on. Am I wrong about the Calendar Class or SimpleDateFormat? If so, could you give me an idea as to how it could be done?
EDIT: Updated answer to go back to a certain day instead of back a certain number of days. Also changed String array to ArrayList
ArrayList<String> tuesdayArrayList = new ArrayList<String>();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_M_d");
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
Date date = new Date();
Date cutoffDate;
int cutoffYear = 2013;
int cutoffMonth = Calendar.JUNE;
int cutoffDayOfMonth = 25;
cutoffDate = new GregorianCalendar(cutoffYear, cutoffMonth, cutoffDayOfMonth).getTime();
while (day != Calendar.TUESDAY) {
calendar.add(Calendar.DATE, 1);
day = calendar.get(Calendar.DAY_OF_WEEK);
}
int i = 0;
while (date.after(cutoffDate)) {
calendar.add(Calendar.DATE, -7);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
date = new GregorianCalendar(year, month, dayOfMonth).getTime();
tuesdayArrayList.add(dateFormat.format(date));
Log.d("myTag: ", tuesdayArrayList.get(i));
i++;
}

How define the proper Day for Date variable

There are two times such as "startTime" = 23:57 and "endTime" = 00:50. How can I define that startTime belongs to the day that is before "endTime"?
Date min = date("23:57");
Date max = date("00:50");
private static Date date(final String time) {
final Calendar calendar = Calendar.getInstance();
String[] hm = time.split(":");
int hour = Integer.parseInt(hm[0]);
int minute = Integer.parseInt(hm[1]);
calendar.set(Calendar.HOUR,hour);
calendar.set(Calendar.MINUTE,minute);
final Date result = calendar.getTime();
return result;
}
you could append a token of some kind, like + to the end your time:
Date max = date("00:50+");
and when parsing the time:
if time.endsWith("+") {
calendar.add(Calendar.HOUR, 24);
}
if you needed to handle periods of longer than 24 hours you could use +1, +2 etc.

Categories