0

I would like to compare the string time format, For example Is there any other api provided by someone?

public void test() {

    Stirng t1 = "10:30 AM"; // 12-hours format
    Stirng t2 = "11:30 AM"; // 12-hours format
            <or>
    Stirng t1 = "10:30"; // 24-hours format
    Stirng t2 = "11:30"; // 24-hours format

    if(t1.before(t2)) {
        System.out.println(t1 + " is before of " + t2);
    }
}
Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131

5 Answers5

6

I would like to compare the string time format

Don't, unless you really have to.

In general - and this is something that has become clearer to me over time, watching many Stack Overflow questions - the sooner you can get your data into a "natural" format, the better. In this case, the natural data format is something representing a time of day, not a string.

So parse all your strings - ideally using Joda Time and its DateTimeFormatter.parseLocalTime method to create LocalTime objects. Then they will be naturally comparable, and also usable for anything else you want to do. Keep the data in its natural form for as long as you can, only converting it to a string or other representation when you absolutely have to, e.g. for serialization to another machine.

Of course, if you can avoid having a string representation at all that would be even better.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

You can try to use Joda Time to parse the time and perform comparisons.

dteoh
  • 5,794
  • 3
  • 27
  • 35
0

Try JodaTime,

For your example it would be

if (new DateTime(2012, 9, 15, 10, 30).compareTo(new DateTime(2012, 9, 15, 11, 30) < 0) {
    // first is before second date
}

EDIT: after Jon's advice

This would be better

if (new LocalTime(10, 30).compareTo(new LocalTime(11, 30) < 0) {
    // first time is before second time
}
RNJ
  • 15,272
  • 18
  • 86
  • 131
  • 1
    `DateTime` isn't an appropriate type to use here - there's no date component, and we don't know the time zone. We have a time of day, which is represented by `LocalTime` in Joda Time. – Jon Skeet Sep 28 '12 at 08:20
  • ah thanks @JonSkeet, I didnt know about LocalTime. – RNJ Sep 28 '12 at 08:22
0

I know nothing about any api for that, but you can convert your string to date

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date time =  formatter.parse("11:30");

then just call method time.compareTo(otherTime)

user902383
  • 8,420
  • 8
  • 43
  • 63
  • SimpleDateFormat formatter = new SimpleDateFormat("HH:mm a") : the small letter 'a' would also enable the parsing of AM/PM –  Sep 28 '12 at 08:32
  • right, and if you want to be more precise, hours can be HH(0-23)/hh(0-11)/KK(1-24)/kk(1-12) – user902383 Sep 28 '12 at 08:39
0

Use Joda Time

DateTimeFormatter.parseLocalTime method gives the time object corresponding to the local time zone.

See this link:

http://joda-time.sourceforge.net/

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75