0

I have a String that contains a Time in the following format:

"hh:mm tt"

For Example you could represent the current time as "7:04 PM"

How can I compare this to the current time in the user's time zone to see if this time is less than, equal to, or greater than the current time?

6
  • I need this to be as efficient as possible since it will be executed in a Service. Commented May 24, 2012 at 0:08
  • if you just have 7:04 PM and not the offset, how do you hope to compare it to an offset time in the users local timezone? Or are your times based off of a specific offset? Commented May 24, 2012 at 0:10
  • They are based on a specific offset. Commented May 24, 2012 at 0:16
  • Personally then I would put the time into a 24hr format and just do the math directly on the hour/minutes/seconds...etc (whatever granularity you need) and then apply the offset to the result. Commented May 24, 2012 at 0:17
  • So you are recommending this as opposed to create Calendar() or Date() objects? Commented May 24, 2012 at 0:19

2 Answers 2

3

You can convert String to Date.

String pattern = "<yourPattern>";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
try {
 Date one = dateFormat.parse(<yourDate>);
 Date two = dateFormat.parse(<yourDate>);

}
catch (ParseException e) {}

It's implements Comparable interface so you should be able to compare them with compareTo()


Edit: I forgot but you know it but only for sure compareTo return -1, 1 or 0 so one.compareTo(two) returns -1 when first ist before second etc.

Sign up to request clarification or add additional context in comments.

Comments

3

The following code elaborates on @Sajmon's answer.

public static void main(String[] args) throws ParseException {
    String currentTimeStr = "7:04 PM";

    Date userDate = new Date();
    String userDateWithoutTime = new SimpleDateFormat("yyyyMMdd").format(userDate);

    String currentDateStr = userDateWithoutTime + " " + currentTimeStr;
    Date currentDate = new SimpleDateFormat("yyyyMMdd h:mm a").parse(currentDateStr);

    if (userDate.compareTo(currentDate) >= 0) {
        System.out.println(userDate + " is greater than or equal to " + currentDate);
    } else {
        System.out.println(userDate + " is less than " + currentDate);
    }
}

2 Comments

Eclipse says that you must surround SimpleDateFormat.parse() with a try catch block.
Yes, this is true. In the code above, the main method throws a ParseException. In your code, just like in @Sajmon's answer, I expect you'll be surrounding parse with a try-catch block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.