简体   繁体   English

Javascript将时间字符串设置为日期对象

[英]Javascript set time string to date object

Please see the below code;请看下面的代码;

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

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 小时的字符串格式时间。

The time will vary.时间会有所不同。 Cannot know what will be the time earlier.不知道更早的时间是什么时候。 Also it is 12 hour time.也是12小时的时间。 So it will be AM or PM所以它将是上午或下午

You can parse the time with a regex, and set the hours and minutes accordingly:您可以使用正则表达式解析时间,并相应地设置小时和分钟:

http://jsfiddle.net/54VkC/1/ http://jsfiddle.net/54VkC/1/

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);

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

The corrected code which handles these cases can be seen here:可以在这里看到处理这些情况的更正代码:

http://jsfiddle.net/54VkC/93/ http://jsfiddle.net/54VkC/93/

 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); }

I'm late to the party, but I thought I'd share a funtion that doesn't use regex:我迟到了,但我想我会分享一个不使用正则表达式的函数:

function setDateTime(date, time) {
    var index = time.indexOf("."); // replace with ":" for differently displayed time.
    var index2 = time.indexOf(" ");

    var hours = time.substring(0, index);
    var minutes = time.substring(index + 1, index2);

    var mer = time.substring(index2 + 1, time.length);
    if (mer == "PM"){
        hours = hours + 12;
    }


    date.setHours(hours);
    date.setMinutes(minutes);
    date.setSeconds("00");

    return date;
}

Using moment.js will be the easy solution.使用moment.js将是简单的解决方案。

const fullDate = new Date();
// fullDate = Tue Dec 12 2017 11:18:30 GMT+0530 (IST) {}
const time = '01.00 AM';
const d = moment(fullDate).format('L'); // d = "12/12/2017"
const date = moment(d +' '+ time).format();
// date = "2017-12-12T01:00:00+05:30"

If you want convert moment date to js date如果要将时刻日期转换为 js 日期

const jsDate = moment(date).toDate();
function getCurrentDate() {
    var lDate = new Date();
    var lDay = lDate.getDate();
    var lMonth = lDate.getMonth() + 1;
    var lYear = lDate.getFullYear();

    if (lDay < 10) {
        lDay = '0' + lDay
    }

    if (lMonth < 10) {
        lMonth = '0' + lMonth
    }
    mCurrentDate = lYear + "-" + lMonth + "-" + lDay + "T00:00:00+05:30";
}

I added a few things as an improvement to the accepted answer by @thebreiflabb to suit my use case and thought i'd share.我添加了一些东西来改进@thebreiflabb 接受的答案,以适应我的用例,并认为我会分享。

if the regex is changed to timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/;如果正则表达式更改为timeReg = /(\d+)[\.|:](\d+)\s?(\w+)/; , it'll handle a few other common cases. ,它将处理其他一些常见情况。

namely:即:

  • using a colon instead of decimal point between hours and minutes在小时和分钟之间使用冒号而不是小数点
  • allowing am/pm to immediately follow the time with no space允许上午/下午立即跟随时间而没有空间

also, setting the seconds to 0 (since that was my main use case)另外,将秒数设置为 0(因为那是我的主要用例)

the resulting code would be:结果代码将是:

var test, parts, hours, minutes, date,
    d = (new Date()).getTime(),
    tests = ['01.25 PM', '01:25pm', '1:25 PM', '11.35 PM', '12.45 PM', '01.25 AM', '11.35 AM', '12.45 AM'],
    i = tests.length,
    timeReg = /(\d+)[\.|:](\d+)\s?(\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);
    date.setSeconds(0);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM