Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare dates in String format

Tags:

java

date

I'm getting two dates as String values and I wanted to check start time is earlier than the end time. I compare them as it is without converting them to date using SimpleDateFormat, like this:

String startTime = "2013-01-02 14:25:56";
String endTime   = "2013-01-02 14:30:56";

if(endTime.compareTo(startTime) > 0){
    System.out.println("End time is greater than start time");
}

Is it really necessary to convert them to date and compare? Will I miss anything? Am I doing the right thing?

like image 549
someone Avatar asked Jan 02 '13 15:01

someone


2 Answers

What you will be missing is the verification if the dates are in fact well-formatted.

If the dates are formatted exactly as you showed every time, then this will work. If there's any chance that it might be different, then parsing and comparing the resulting Date objects will add at least somewhat of a check.

For example if one of the two dates happens to be formatted as 2013.01.02 14:30:56 or it even included an unformatted date such as yesterday then your code would silently assume some order (that most likely has little to do with the actual order) and proceed. What it should do is notify the user (or the log file, ...) that some expectation was not met.

like image 139
Joachim Sauer Avatar answered Oct 06 '22 23:10

Joachim Sauer


Is it really necessary to convert them to date and compare?

If you don't have to include timezones and can ensure that you always have this format the lexical order will work.

Will I miss anything?

You lose the flexibility

Am I doing the right thing?

That depends on the point of view. I use something similar in a specialized search-enginge (only for performance reasons). Usually I convert to Date and compare these objects.

like image 23
stacker Avatar answered Oct 06 '22 23:10

stacker