Java Date comparison not working properly - java

I am getting actual date using this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
Calendar cal = Calendar.getInstance();
String today = dateFormat.format(cal.getTime());
System.out.println(today);
It prints today`s date: 21.04.2014
Then, I want to compare this date whether it is between two dates:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date actualdate = sdf.parse(today);
Date date1 = sdf.parse("20.04.2014");
Date date2 = sdf.parse("23.04.2014");
Calendar actual = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
actual.setTime(actualdate);
cal1.setTime(date1);
cal2.setTime(date2);
if(actual.after(date1) && actual.before(date2)) System.out.println("Yes");
else System.out.println("No");
It always prints No. What is the problem ? When I set date1 to 21.04.2014 and use actual.equals(date1) it works. But when I am using before or after it doesnt. Thanks

change it to actual.after(cal1) && actual.before(cal2)

you are comparing a calendar with dates
you must compare calendars with calendars or dates with dates
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Cal {
public static void main(String[] args) throws ParseException {
SimpleDateFormat dateFormat = new SimpleDateFormat("ddMMyyyy");
Calendar cal = Calendar.getInstance();
String today = dateFormat.format(cal.getTime());
System.out.println(today);
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
Date actualdate = sdf.parse(today);
Date date1 = sdf.parse("20042014");
Date date2 = sdf.parse("23042014");
Calendar actual = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
actual.setTime(actualdate);
cal1.setTime(date1);
cal2.setTime(date2);
System.out.println(actual);
System.out.println(cal1);
System.out.println(cal2);
if(actualdate.after(date1) && actualdate.before(date2)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
if(actual.after(cal1) && actual.before(cal2)){
System.out.println("Yes");
}
else {
System.out.println("No");
}
}
}

I am sorry to tell you that the function that compares between two dates is useless and not working.
If you would like to have a go this is the function i tested
private static boolean validateEndDate(String startDate, String endDate)
{
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy");
Date date1 = dateFormat.parse(startDate);
Date date2 = dateFormat.parse(endDate);
if(date1.before(date2))
{
return true;
}
}catch(Exception e)
{
System.out.println(e.getMessage());
}
return false;
}
Now to see what i am talking about give it these two dates:
System.out.println(validateEndDate("31/07/2016","1/08/2016"));
Now to fix this problem i had to implement my own function:
private boolean compareDates(String startDate,String endDate)
{
int day=Integer.parseInt(startDate.split("/")[0]);
int month=Integer.parseInt(startDate.split("/")[1]);
int year=Integer.parseInt(startDate.split("/")[2]);
int day2=Integer.parseInt(endDate.split("/")[0]);
int month2=Integer.parseInt(endDate.split("/")[1]);
int year2=Integer.parseInt(endDate.split("/")[2]);
if(year<year2 || year==year2)
{
if(year<year2)
{
return true;
}
//Check the month
if(month<month2 || month==month2)
{
if(month<month2)
{
return true;
}
//Check the day
if(day<day2)
{
return true;
}
}
}
return false;
}

You are comparing Calender value with Date. Just use Date values. or just use Calender values. Don't mix them both.
actual.after(cal1) && actual.before(cal2)
or
actualdate.after(date1) && actualdate.before(date2)

see the working one:
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy");
Date actual = sdf.parse("21.04.2014");
Date date1 = sdf.parse("20.04.2014");
Date date2 = sdf.parse("23.04.2014");
if(actual.after(date1) && actual.before(date2)) {
System.out.println("Yes");
} else {
System.out.println("No");
}

Related

How can I increment the day with skipping weekends [duplicate]

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();
}

How to get the Calendar dates in between?

I want to get the dates in between the calendar, but for some reason this does not work. Any suggestions why? Thanks.
public boolean verifyDate(Calendar cal) {
Calendar toDate = Calendar.getInstance();
toDate.setTime(passToDate);
Calendar fromDate = Calendar.getInstance();
fromDate.setTime(passFromDate);
return !((fromDate.after(cal) && toDate.before(cal)) || DateUtils.isSameDay(fromDate, cal) || DateUtils.isSameDay(toDate, cal));
}
fromDate.after(cal) - will return true if fromDate will be after the cal, similar thing with before.
If you want to check that cal is between two dates use:
return cal.after(fromDate) && cal.before(toDate)
&& !(DateUtils.isSameDay(fromDate, cal) || DateUtils.isSameDay(toDate, cal));
public static List<String> getDates(String startDate, String endDate)
throws ParseException, java.text.ParseException {
List<String> dateList = new ArrayList<String>();
if (startDate == null || startDate.equals("") || endDate == null || endDate.equals("")) {
return null;
}
Calendar calendar = new GregorianCalendar();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = dateFormat.parse(startDate);
Date d2 = dateFormat.parse(endDate);
Calendar calendar2 = new GregorianCalendar();
calendar2.setTime(d2);
calendar2.add(Calendar.DATE, 1);
calendar.setTime(d1);
while (calendar.getTime().before(calendar2.getTime()))
{
Date result = calendar.getTime();
dateList.add(dateFormat.format(result));
calendar.add(Calendar.DATE, 1);
}
return dateList;
}

get list of dates which occurs between two dates

I am trying to get dates, which occurs in every 5 days from start date to end date.
Eg.
if start date= 11/10/2014 i.e MM/DD/YYYY format
and end date =11/26/2014
then my **expected output** is =
[11/15/2014,11/20/2014,11/25/2014]
I tried below but very confuse where to run loop for getting exact ouput. Currently from below code i am only getting 1 date in list
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class TestDate {
// mm/dd/yyyy
public List getDates(Date fromDate,int frequency,Date endDate){
List list=new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(fromDate); // Now use today date.
c.add(Calendar.DATE, frequency); // Adding 5 days
String newDate = sdf.format(c.getTime());
String sEndDate=sdf.format(endDate);
if((newDate.compareTo(sEndDate) < 0) || (newDate.compareTo(sEndDate) == 0)){
list.add(newDate);
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
public static void main(String[] args) {
try {
TestDate obj=new TestDate();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date s = sdf.parse("11/10/2014");
Date e = sdf.parse("11/26/2014");
System.out.println(obj.getDates(s, 5, e));
}
catch(Exception e) {
System.err.println("--exp in main---"+e);
}
}
}
Correct answer is below *Thanks to Almas*
public List getDates(Date fromDate,int frequency,Date e){
List list=new ArrayList<Date>();
Calendar c = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c2.setTime(e); // Now use today date.
Date endDate=c2.getTime();
Date newDate=fromDate;
while(true){
c.add(Calendar.DATE, frequency);
newDate=c.getTime();
if(newDate.compareTo(endDate)<=0){
list.add(newDate);
}else{
break;
}
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
Why do you want date to be as string and compared lexicographically instead of comparing them as date?
String newDate = sdf.format(c.getTime());
String sEndDate=sdf.format(endDate);
This should be changed as
Date newDate = c.getTime();
Also you are using two if condition which you could do in one like below :
if (newDate.compareTo(endDate) <= 0) {
list.add(newDate);
}
as far as looping is concerned you should do it in your getDates method like below:
Date newDate;
while (true) {
c.add(Calendar.DATE, frequency); // Adding 5 days
newDate = c.getTime();
if (newDate.compareTo(endDate) <= 0) {
list.add(newDate);
} else {
break;
}
}
Make use of Apache commons DateUtils. This will make your code simple
Date tempDate = DateUtils.addDays(fromDate, frequency);
while (tempDate.before(endDate))
{
list.add(tempDate);
tempDate = DateUtils.addDays(tempDate, frequency);
}
return list;
try this one
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class NewClass1 {
// mm/dd/yyyy
public List getDates(Date fromDate, int frequency, Date endDate) {
List list = new ArrayList<Date>();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(fromDate); // Now use today date.
c.add(Calendar.DATE, frequency); // Adding 5 days
String newDate = sdf.format(c.getTime());
//System.out.println("date"+newDate);
String formDate = sdf.format(fromDate);
String sEndDate = sdf.format(endDate);
int x = 1;
while (((newDate.compareTo(sEndDate) > 0) || (newDate.compareTo(sEndDate) != 0)) && x < frequency) {
c.add(Calendar.DATE, frequency);
sEndDate = sdf.format(c.getTime());
x++;
System.out.println("date: " + sEndDate);
list.add(newDate);
}
//Weekly=7,Bi-Weekly14,Monthly-30,Semi-Monthly-15
return list;
}
public static void main(String[] args) {
try {
NewClass1 obj = new NewClass1();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date s = sdf.parse("11/10/2014");
Date e = sdf.parse("11/26/2014");
obj.getDates(s, 5, e);
} catch (Exception e) {
System.err.println("--exp in main---" + e);
}
}
}

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

How to get every day except weekend or Saturday or Sunday between two dates in java?

hi all how to generate dates if the start date and end date are provided in java?
like the following :
Ex : if the start date is 15-04-2012 and end date is 15-06-2012 having this i want dates to be like the following and the list should omit saturday and sunday
1.15-04-2012,
2.16-04-2012,
3.17-04-2012,
.
.
.
.
.
.
15-06-2012
I have done like the following but it will generate for one month if the date range is of same month.
`
public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, int month, int day){
int totalworkingdays=0,noofdays=0;
String nameofday = "";
ConcurrentHashMap<String,String> workingDaysMap = new ConcurrentHashMap<String,String>();
Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
noofdays = findNoOfDays(year,month,day);
for (int i = 1; i <= noofdays; i++) {
Date date = (new GregorianCalendar(year,month - 1, i)).getTime(); // year,month,day
SimpleDateFormat f = new SimpleDateFormat("EEEE");
nameofday = f.format(date);
String daystr="";
String monthstr="";
if(i<10)daystr="0";
if(month<10)monthstr="0";
String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;
if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
workingDaysMap.put(formatedDate,formatedDate);
totalworkingdays++;
}
}
return workingDaysMap;
}
So please do advice me how to go about.
Regards
Tony
int noOfDaysBetween = 5;
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
for(int index = 0 ; index < noOfDaysBetween; index++){
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
if( dayOfWeek!=Calendar.SUNDAY && dayOfWeek!=Calendar.SATURDAY) {
System.out.println(cal.getTime());
}
cal.add(Calendar.DATE, 1);
}
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
//15-04-2012
calendar.set(Calendar.DAY_OF_MONTH, 15);
calendar.set(Calendar.YEAR, 2012);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MONTH, 3);
Date start = calendar.getTime();
//15-06-2012
calendar.set(Calendar.MONTH, 5);
Date end = calendar.getTime();
calendar.setTime(start);
Date d = null;
while((d = calendar.getTime()).before(end) || d.equals(end)) {
int day = calendar.get(Calendar.DAY_OF_WEEK);
if (day != Calendar.SATURDAY && day != Calendar.SUNDAY) {
System.out.println(d);
}
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
}
I prefer usage of LocalDate.
import java.time.DayOfWeek;
import java.time.LocalDate;
public class Game {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2018, 6, 1);
LocalDate end = LocalDate.of(2018, 8, 1);
LocalDate d = start;
while(d.compareTo(end) <= 0) {
if (d.getDayOfWeek() != DayOfWeek.SATURDAY && d.getDayOfWeek() != DayOfWeek.SUNDAY) {
System.out.println(d);
}
d = d.plusDays(1);
}
}
}
use the following joda-time
import org.joda.time.DateTimeConstants;
import org.joda.time.LocalDate;
public class DatesexcludingWeekend {
public static void main(String[] args) {
final LocalDate start = new LocalDate(2012, 06, 15);
final LocalDate end = new LocalDate(2012, 07, 14);
LocalDate weekday = start;
if (start.getDayOfWeek() == DateTimeConstants.SATURDAY|| start.getDayOfWeek() == DateTimeConstants.SUNDAY) {
weekday = weekday.plusWeeks(1).withDayOfWeek(DateTimeConstants.MONDAY);
}
while (weekday.isBefore(end)) {
System.out.println(weekday);
if (weekday.getDayOfWeek() == DateTimeConstants.FRIDAY)
weekday = weekday.plusDays(3);
else
weekday = weekday.plusDays(1);
}
}

Categories