Javascript set time string to date object

后端 未结 5 959
野性不改
野性不改 2020-12-06 05:13

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 wa

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-06 05:28

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

提交回复
热议问题