tarquin tarquin - 1 month ago 9
Java Question

comparing two date objects of different formats

I have two dates.

The first date is the system time. The second date is related to a news article and when the article expires, it is called end_time.

Im using selenium to test that the article does in fact expire when the system time exceed the the end_time.

My code is as follows:

String searchstring = poriginal;
//make objects to be compared
Date parsed_system_time=null;
Date parsed_end_time=null;

//generate a current time object
GenerateSimpleTime current_time = new GenerateSimpleTime();
current_time.setSystem_time_snapshot();
String system_time = current_time.getSystem_time_snapshot();


//set up the SimpleDateFormat to be used for parsing the strings into objects for comparison
//parsing the date format e.g : 04:11:2016 11:34 AM
SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy hh:mm");
try{
System.out.println("Trying to parse system time: \n");
parsed_system_time = sdf.parse(system_time);
}
catch(ParseException e)
{
System.out.println("Couldnt parse system time...\n");
e.printStackTrace();
}

SimpleDateFormat end_time_sdf = new SimpleDateFormat("dd MMMM, yyyy hh:mm a");
try {
parsed_end_time = end_time_sdf.parse(end_date);
} catch (ParseException e) {
System.out.println("Couldnt parse end_date...\n");
e.printStackTrace();
}

while(parsed_system_time.before(parsed_end_time))
{
current_time.setSystem_time_snapshot();
try {
system_time = current_time.getSystem_time_snapshot();
parsed_system_time = sdf.parse(system_time);
System.out.println("endtime is: "+ parsed_end_time+"\n");
} catch (ParseException e) {
System.out.println("Couldnt parse current_time.getSystem_time_snapshot()...\n");
e.printStackTrace();
}
//System.out.println("system time is: \n");
}


When i run the program the dates are in the following format

endtime: Fri Nov 04 13:49:00 AEST 2016

systemtime: 04:11:2016 1:52 PM

if it a problem when comparing the two dates if they are in a different format. It shouldn't matter right?

When I run the test my program goes and runs indefinitely and doesnt detect when system time is greater than the end time.

The setSystem_time_snapshot() does the following:

String pattern= "dd:MM:YYY h:mm a";
SimpleDateFormat simpletime = new SimpleDateFormat(pattern);
system_time_snapshot = simpletime.format(new Date());

System.out.println("system time snapshop is "+system_time_snapshot+"\n");


Any ideas where I clean up this mess and get it working properly?

Answer

So your setSystem_time_snapshot() is returning a string in the format of

dd:MM:YYY h:mm a

But your sdf is

SimpleDateFormat sdf = new SimpleDateFormat("dd:MM:yyyy hh:mm");