Js 日期转换函数(UTC时间转换及日期想加减)

时间:2022-02-05 20:10:08

IOS上Js日期转换中new Date("yyyy-mm-dd")不能正常工作,必须使用new Date("yyyy/MM/dd");

日期相加减:

Date.prototype.DateAdd = function (strInterval, Number) {
    var dtTmp = this;
    switch (strInterval) {
        case 's': return new Date(Date.parse(dtTmp) + (1000 * Number));
        case 'n': return new Date(Date.parse(dtTmp) + (60000 * Number));
        case 'h': return new Date(Date.parse(dtTmp) + (3600000 * Number));
        case 'd': return new Date(Date.parse(dtTmp) + (86400000 * Number));
        case 'w': return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
        case 'q': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'm': return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
        case 'y': return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    }
}

将日期转换成UTC时间。

//return utc date
function getUTCtime(date) {

var UTCyear = date.getUTCFullYear();
    var UTCmonth = date.getUTCMonth() + 1;
    var UTCday = date.getUTCDate();
    var UTChours = date.getUTCHours();
    var UTCmin = date.getUTCMinutes();
    var UTCseconds = date.getUTCSeconds();
    var UTCtimeStr = UTCyear + "/" + UTCmonth + "/" + UTCday + " " + UTChours + ":" + UTCmin + ":" + UTCseconds;
    return new Date(UTCtimeStr);

}