I am converting two different dates format into local time zone and in single format using simple date format, then comparing whether they are equal or not. My code is not able to convert From date given in code.
My code is working fine when i provide from date in "Sep 11, 2019 - 1:00 am BRT/BRDT" AM but its getting failed for PM time. Sample date is "Sep 11, 2019 - 1:00 pm BRT/BRDT".
public class DateSample {
public static void main(String[] args) throws ParseException {
DateSample obj = new DateSample ();
String str= obj.dateCompare(
"MMM dd,yyyy - HH:mm aaa z",
"yyyy-MM-dd'T'HH:mm:ss.SSSXXX",
"Sep 11, 2019 - 1:00 pm BRT/BRDT",
"2019-09-11T13:00:00.000-03:00"
);
System.out.println(str);
}
String dateCompare(String fromDateFormat, String toDateFormat,String fromdate, String todate)throws ParseException{
String CheckFormat = "MMMMM yyyy HH:mm:ss.SSSZ";
String dateStringFrom;
String dateStringTo;
Date DF = new Date();
Date DT = new Date();
int flagtodate=0;
int flagfromdate=0;
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat FromDF = new SimpleDateFormat(fromDateFormat);
FromDF.setLenient(false);
Date FromDate = FromDF.parse(fromdate);
dateStringFrom = new SimpleDateFormat(CheckFormat).format(FromDate);
DateFormat FromDF1 = new SimpleDateFormat(CheckFormat);
DF=FromDF1.parse(dateStringFrom);
System.out.println("From Date is ok = " + dateStringFrom);
}
catch (ParseException e)
{
flagfromdate = 1;
}
catch (IllegalArgumentException e)
{
flagfromdate = 1;
}
try
{
//DateFormatdf = DateFormat.getDateInstance(DateFormat.SHORT);
DateFormat ToDF = new SimpleDateFormat(toDateFormat);
ToDF.setLenient(false);
Date ToDate = ToDF.parse(todate);
dateStringTo = new SimpleDateFormat(CheckFormat).format(ToDate);
DateFormat ToDF1 = new SimpleDateFormat(CheckFormat);
DT=ToDF1.parse(dateStringTo);
System.out.println("To Date is ok = " + dateStringTo);
}
catch (ParseException e)
{
flagtodate=1;
}
catch (IllegalArgumentException e)
{
flagtodate=1;
}
if(flagfromdate == 0 &&flagtodate==0)
{
if(DF.equals(DT))
{
// if the date is same
return "FromDate and ToDate are same";
}
else if(DF.before(DT))
{
//if the from date is before the to date
return "FromDate is less than ToDate";
}
else
{
// if the date from is after the to date
return "FromDate is greater than the ToDate";
}
}
return "Error";
}
}
Below mentioned is the output from console in failure case:
To Date is ok = September 2019 21:30:00.000+0530
Error
Success case output:
From Date is ok = September 2019 09:30:00.000+0530
To Date is ok = September 2019 21:30:00.000+0530
FromDate is less than ToDate