js time conversion and time comparison

Time conversion is often encountered in development. This rookie will take you to summarize. If it is missing something, or where it is written incorrectly. Please advise~

The timestamp is converted to yyyy-mm-dd hh:mm:ss:

//1614544999000 => 2021-03-01 04:43:19
//如果获取某一时间戳对应的年月日时分秒就按照下面的形式。如果获取当前时间,就去掉参数time,var date = new Date(time);改成var date = new Date();就可以啦
function getTime(time) {
    var date = new Date(time);
    var year = date.getFullYear();
    var month= date.getMonth() + 1;
    month= checkTime(month);
    var day = date.getDate();
    day = checkTime(day);
    var hour = date.getHours();
    hour=checkTime(hour);
    var min = date.getMinutes();
    min=checkTime(min);
    var seconds= date.getSeconds();
    seconds=checkTime(seconds);
    return year + '-' + month + '-' + day + ' ' + hour + ':' +min + ':' +seconds;
}

function checkTime(m) {
    if (m < 10) {
        m = "0" + m;
    }
    return m;
}


Convert json serialization to yyyy-mm-dd hh:mm:ss:

// /Date(1614544999000)/ => 2021-03-01 04:43:19
//后台返回的数据有可能是/Date(1614544999000)/ 形式的,那么就用以下方法,是的没错,就比上面的多了一点点东西而已啦
function getTime(time) {
    var date = new Date(parseInt(time.slice(6, 19)));
或者var date = new Date(parseInt(time.replace("/Date(", "").replace(")/", ""), 10));
    var year = date.getFullYear();
    var month= date.getMonth() + 1;
    month= checkTime(month);
    var day = date.getDate();
    day = checkTime(day);
    var hour = date.getHours();
    hour=checkTime(hour);
    var min = date.getMinutes();
    min=checkTime(min);
    var seconds= date.getSeconds();
    seconds=checkTime(seconds);
    return year + '-' + month + '-' + day + '&nbsp;' + hour + ':' +min + ':' +seconds;
}

function checkTime(m) {
    if (m < 10) {
        m = "0" + m;
    }
    return m;
}

Time in DateTime format (such as 2021/1/15 20:34:30) is converted to yyyy-mm-dd (such as 2021-01-15):

var date=time.ToString("yyyy-MM-dd");

Compare the specified time with the current time

//time指定时间,gap相差天数
//如果time不是时间戳形式,加个转换就可以了
function getGap(time,gap) {
    time = new Date(time);
    var currentDate = new Date();
    var gap = time.getTime()-currentDate.getTime();
    var gapDay = parseInt(gap / (1000 * 60 * 60 * 24));
    if (gapDay <= gap) {
        return true;
    }else{
        return false;
    }
}

getGap(1614544999000,30);

 

Guess you like

Origin blog.csdn.net/weixin_45042290/article/details/112686092