开发者

Time interval in 15-minutes increment format

开发者 https://www.devze.com 2023-02-23 05:23 出处:网络
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.

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消