2

I was having some difficulties when trying to compare current time with the time I retrieved from textfile. The time from my textfile is in 12 hours format, eg 12:30 PM. Currently I have this code which is comparing the time in 24-hours format, I not sure how to convert it to compare between time in 12-hours format:

public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(compareStringOne);
    dateCompareTwo = parseDate(compareStringTwo);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //yada yada
    }
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}

Thanks in advance.

1 Answers1

0

Use h:mm a instead of HH:mm as the input format.

public static final String inputFormat = "h:mm a";
  • h stands for hour in AM/PM (1-12)
  • mm stands for minute in hour
  • a stands for AM or PM

Also note that your two example test strings are missing the AM/PM marker.

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156