我想从当前时间减去8小时。如果我尝试从小时减去8,那就是负数

时间:2016-12-13 17:36:00

标签: javascript datetime

我正在使用UTC时间,想要从当前时间减去8小时。我正在使用JavaScript。

函数getUTCStartDate(time){

    var d = new Date();
    var year = d.getUTCFullYear();
    var month = (d.getUTCMonth() + 1);
    var date = d.getUTCDate();
    var hours = d.getUTCHours();
    var hoursMinusTime = (d.getUTCHours() - time);
    var minutes = d.getUTCMinutes();
    var seconds = d.getUTCSeconds();
    var millisec = d.getUTCMilliseconds();

    date = date.toString().length > 1 ? date : '0' + date;
    month = month.toString().length > 1 ? month : '0' + month;
    hoursMinusTime = hoursMinusTime.toString().length > 1 ? hoursMinusTime : '0' + hoursMinusTime;
    minutes = minutes.toString().length > 1 ? minutes : '0' + minutes;
    seconds = seconds.toString().length > 1 ? seconds : '0' + seconds;
    millisec = millisec.toString().length > 1 ? millisec : '0' + millisec;


    return year + "-" + month + "-" + date + "T" + hoursMinusTime + ":" + minutes + ":" + seconds + "." + millisec + "Z";
}

1 个答案:

答案 0 :(得分:1)

我以不同的方式做到了。将unix时间转换为8小时的时间。

var currTime = new Date();
var d = new Date(currTime.getTime() - (time * 3600000));
var hours = d.getUTCHours();