1

I have a textbox labelled 'Time' which accepts 12-hour or 24-hour time and converts it to 12-hour format i.e (hh:mma) format.

My requirement is to now convert time to 15 min increments format.

For eg:

If user enters 01:10a , it should be converted to 01:15a automatically.

Special cases:

If user enters 11:53a , it should be converted to 12:00p (notice am/pm value changes here)

If user enters 11:53p, it should be converted to 12:00a (notice am/pm value changes here)

This needs to be done within a javascript function.

Please suggest what logic I should use for this conversion.

1 Answer 1

2

You can use the fact that date deals with 60 minutes correctly to do this.

var parts, d, s = '11:55pm';
if (parts = /(\d+):(\d+)(\w+)?/.exec(s)) {
    // date is good
    d = new Date();
    if (parts[3] == undefined) {
        // 24 hr
        d.setHours(parseInt(parts[1]));
    } else {
        d.setHours(parseInt(parts[1]) + ((parts[3].indexOf('a') >= 0) ? 0 : 12));
    }
    // if this is 60, wraps hours...
    d.setMinutes(Math.round(parseInt(parts[2])/15)*15);
    alert(d.toString());
}

At the end, just access the d with the functions here and format as needed.

2
  • Note: this deals correctly with 12 vs. 24 hour time as well as format checking.
    – Sajid
    Apr 11, 2011 at 4:32
  • @gin: You're welcome. If this is the complete answer, please mark the question as answered so that the thread is closed.
    – Sajid
    Apr 11, 2011 at 19:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.