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
Related
This question already has answers here:
How can I add business days to the current date in Java?
(14 answers)
Closed 6 years ago.
How can I increment the day with skipping weekends. I mean if day=Friday then day+1=Monday. Please take a look at my increment method which I increment a calendar day and not a Business day
public Date incDay( Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
I need to modify this method for resolve this issue.
Update:
I update my method like this
public Date incDay(Date date){
final Calendar cal = Calendar.getInstance();
cal.setTime(date);
// public final static int FRIDAY = 6;
final int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
}else{
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
return cal.getTime();
}
Main():
public static void main(String[] args) throws ParseException {
Date d=incBusiness(new Date(2017, 02, 17));//2017/02/18
}
I got 2017/02/18 instead of 2017/02/20
Calendar class has constants to check the day of the week:
FRIDAY is the 6th day of the week, doing an if-else can resolve the issue...
public static void foo() throws ParseException {
String dateString = "2017/02/17";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");// "2017/02/17";
Date date = df.parse(dateString);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) {
cal.add(Calendar.DATE, 3);
} else {
cal.add(Calendar.DATE, 1);
}
System.out.println(cal.getTime());
}
Gets date instance and add no. of days excluding weekends. Set date to next monday if provided date is weekend.
public Date addDays(Date date, int days){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
//set date to next monday if provided date day is weekend
//use this section according to your need.
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY){
cal.add(Calendar.DATE,2);
//days-= 2;
}else if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY){
cal.add(Calendar.DATE,1);
//days--;
}
//add days one by one
while(days > 0){
//if current day is friday add 3 days to skip saturday and sunday
if(cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY){
cal.add(Calendar.DATE,3);
//else add one day
}else{
cal.add(Calendar.DATE,1);
}
//decrements day counter
days--;
}
return cal.getTime();
}
I needed to define start/end dates for a person's given age. This seemed simple:
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(dateOfBirth);
cal.add(Calendar.YEAR, years);
Date start = cal.getTime();
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date end = cal.getTime();
Ah, but then there are those born on Leap Day Feb 29th. If the age is not a multiple of 4 then Calendar will round down to the 28th. In this case, my code above will give a date range ending on Feb 27th, and there'll be a gap.
So, I can easily solve this by checking for this condition, and I can wrap the fix up in some method to avoid duplicating it everywhere. But I'm wondering, is there a better solution I'm not aware of? Something that automatically accounts for this special case for a "day before/after" problem?
Here's my solution:
public static Date getAgeStartEnd(Date d, int age, boolean end) {
if (d == null) return null;
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(d);
int baseDay = cal.get(Calendar.DAY_OF_MONTH);
cal.add(Calendar.YEAR, age + (end ? 1 : 0));
int newDay = cal.get(Calendar.DAY_OF_MONTH);
boolean roundedDown = baseDay != newDay;
if (end && !roundedDown)
cal.add(Calendar.DAY_OF_MONTH, -1);
else if (!end && roundedDown)
cal.add(Calendar.DAY_OF_MONTH, 1);
d = cal.getTime();
return d;
}
Date start = getAgeStartEnd(dateOfBirth, years, false);
Date end = getAgeStartEnd(dateOfBirth, years, true);
This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 7 years ago.
I used a basic technique to implement a method that finds the date of the next day based on the given parameter in the format YYYY-MM-DD and returns the next day in the same format.
Can you please take a look at the code and tell me if it is inefficient or not? It works perfectly fine, but I would prefer to implement a method with more efficiency and fewer lines of code if possible. Keep in mind that any values of the month or day that are single digits numbers have to be formatted with a 0 in the tens place.
public String nextDate(String date){ //ex: 2016-01-31 -returns-> 2016-02-01
int MMrange = 30;
String result = "";
String daystr = date.substring(8,10);
String monthstr = date.substring(5,7);
int day = Integer.parseInt(daystr);
int month = Integer.parseInt(monthstr);
int year = Integer.parseInt(date.substring(0,4));
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12) MMrange = 31;
else if(month==2) MMrange = 28;
if(year%4==0&&month==2) MMrange = 29;
if(day==MMrange){
day =1;
month++;
}else if(month==12&&day==31){
year++;
month = 1;
day = 1;
}else{
day++;
}
result = Integer.toString(year)+"-"+Integer.toString(month)+"-"+Integer.toString(day);
if(month <=9&&day<=9) result = Integer.toString(year)+"-0"+Integer.toString(month)+"-0"+Integer.toString(day);
else if(month <= 9) result = Integer.toString(year)+"-0"+Integer.toString(month)+"-"+Integer.toString(day);
else if(day <= 9) result = Integer.toString(year)+"-"+Integer.toString(month)+"-0"+Integer.toString(day);
return result;
}
Try this...
Updated
// imports...
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public static String getNextdt(String dt) {
try {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
final Date date = format.parse(dt);
final Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(format.format(calendar.getTime()));
return format.format(calendar.getTime());
} catch (Exception e) {
}
}
You should use a java.text.DateFormat for format and a java.util.Calendar for calculation like
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_MONTH, 1);
return df.format(cal.getTime());
A shorter way, provided that you use Java 8 is:
LocalDate localDate = LocalDate.now();
localDate.plusDays(1);
System.out.println(localDate.toString());
Hope this works for you.
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++;
}
I've written this simple method to give me the date of every pay period and it has ceased to work as of January first. I'm really not sure what's wrong here. It doesn't return anything.
public static List<Date> getPayPeriodDatesSinceStartOfYear() {
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Calendar currentDate = new GregorianCalendar();
currentDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
int counter = 2;
List<Date> dates = new ArrayList<Date>();
while ((cal.getTime().compareTo((currentDate.getTime())) <= 0)) {
dates.add(cal.getTime());
counter += 2;
cal.set(Calendar.WEEK_OF_YEAR, counter);
}
java.util.Collections.reverse(dates);
if(dates.isEmpty()){
JOptionPane.showMessageDialog(null, "NO DATES, SOMETHING IS WRONG!");
}
return dates;
}
Your while condition is not being met, the way you have it set up cal is greater than currentDate therefore the while loop never happens.
Calendar cal = new GregorianCalendar();
cal.add(Calendar.WEEK_OF_YEAR, 1);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
cal.set(Calendar.WEEK_OF_YEAR, 2);
Why are you setting week to 1 and then to 2?
(cal.getTime().compareTo((currentDate.getTime())) <= 0)
See the doc for Date. It has methods like before(Date when) and after(Date when).