本文介绍了Javascript将时间字符串设置为日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅以下代码;

var d = new Date();
var s = "01.00 AM";
d.setTime(s);

我知道这段代码错了。请给我正确的设置时间的方法。我手里有12小时的字符串格式。

I know this code is wrong. Please give me the correct way to set the time. I have 12 hour time in string format in my hand.

时间会有所不同。不知道早些时候会是什么时候。也是12小时的时间。因此它将是AM或PM

推荐答案

您可以使用正则表达式解析时间,并设置小时和分钟相应:

You can parse the time with a regex, and set the hours and minutes accordingly:

var d = new Date(),
    s = "01.25 PM",
    parts = s.match(/(\d+)\.(\d+) (\w+)/),
    hours = /am/i.test(parts[3]) ? parseInt(parts[1], 10) : parseInt(parts[1], 10) + 12,
    minutes = parseInt(parts[2], 10);

d.setHours(hours);
d.setMinutes(minutes);

alert(d);

编辑1:
正如jaisonDavis指出的那样,原始代码不适用于12.XX的AM或PM,这是一个疏忽,因为我自己从不使用12小时格式,认为它从00.00开始是错误的。

Edit 1:As jaisonDavis pointed out, the original code will not work for AM or PM for 12.XX, which was an oversight since I never use 12-hour format myself, thinking it started at 00.00 which was wrong.

处理这些案例的更正代码可以在这里看到:

The corrected code which handles these cases can be seen here:


var test, parts, hours, minutes, date,
    d = (new Date()).getTime(),
    tests = ['01.25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
    i = tests.length,
    timeReg = /(\d+)\.(\d+) (\w+)/;

for(; i-- > 0;) {
    test = tests[i];

    parts = test.match(timeReg);

    hours = /am/i.test(parts[3]) ?
        function(am) {return am < 12 ? am : 0}(parseInt(parts[1], 10)) :
        function(pm) {return pm < 12 ? pm + 12 : 12}(parseInt(parts[1], 10));

    minutes = parseInt(parts[2], 10);

    date = new Date(d);

    date.setHours(hours);
    date.setMinutes(minutes);

    console.log(test + ' => ' + date);
}

这篇关于Javascript将时间字符串设置为日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-05 04:45