使用javascript将时间转换为分钟或秒

时间:2016-10-19 13:14:19

标签: javascript time

我希望以24小时格式显示时间,但在我的代码中,问题是它显示日期:分钟(18:20)之后我需要在几分钟或几秒内转换该时间。

 var time = "18/10/2016 7:20:50 PM";
        var hours = Number(time.match(/^(\d+)/)[1]);
        var minutes = Number(time.match(/:(\d+)/)[1]);
        var AMPM = time.match(/\s(.*)$/)[1];
        if (AMPM == "PM" && hours < 12) hours = hours + 12;
        if (AMPM == "AM" && hours == 12) hours = hours - 12;
        var sHours = hours.toString();
        var sMinutes = minutes.toString();
        if (hours < 10) sHours = "0" + sHours;
        if (minutes < 10) sMinutes = "0" + sMinutes;
        stime = (sHours + ":" + sMinutes);
    	sstime = stime.toString();
    	document.write(sstime);

2 个答案:

答案 0 :(得分:2)

您的hours正则表达式错误,请尝试这种简单的方法来提取小时和分钟

var items = time.split( " " )[1].split(":");
var hours = Number(items[0]);
var minutes = Number(items[1]);

你的其余逻辑应该没问题。

var time = "18/10/2016 7:20:50 PM";
var items = time.split(" ")[1].split(":");
var hours = Number(items[0]);
var minutes = Number(items[1]);
var AMPM = time.split(" ")[2];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
stime = (sHours + ":" + sMinutes);
sstime = stime.toString();
console.log(sstime);

答案 1 :(得分:1)

dt = new Date();
    var m = dt.getMonth() + 1;
    var y = dt.getFullYear();
    var d = dt.getDate();
    var mm = dt.getMinutes();
    var h = dt.getHours();
    var s = dt.getSeconds();
    if (m < 10)
        m = "0" + m;
    if (d < 10)
        d = "0" + d;

    if (h < 10)
        h = "0" + h;
    if (mm < 10)
        mm = "0" + mm;
    if (s < 10)
        s = "0" + s;
    console.log( y + "-" + m + "-" + d + " " + h + ":" + mm + ":" + s);
    console.log( y + "-" + m + "-" + d);