放置一个时间生成

放置一个时间获取的函数 省的每次到处搜

function getDay(num, str) {
    var today = new Date();
    var nowTime = today.getTime();
    var ms = 24*3600*1000*num;
    today.setTime(parseInt(nowTime + ms));
    var oYear = today.getFullYear();
    var oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) oMoth = '0' + oMoth;
    var oDay = today.getDate().toString();
    if (oDay.length <= 1) oDay = '0' + oDay;
    return oYear + str + oMoth + str + oDay;
}

调用直接如下

var yesterday = getDay(-1, '-');
console.log(yesterday);

获取昨天/前天的日期如果要获取昨天的日期,num就是-1, 前天的就是-2,依次类推。str表示年月日间的分割方式。

比如我要得到昨天的日期,用短横线‘-’连接。控制台输出结果:

2020-10-28

判断是否超过12点,未超过为前天日期,超过为昨天日期

timeForChange() {
            let dayFor12 = new Date(new Date(new Date().toLocaleDateString()).getTime() + 12 * 60 * 60 * 1000 );
            let dayDate = new Date().getTime();
            let yesterdayTime = this.getDay(-1, '-');
            let beforeYesterdayTime = this.getDay(-2, '-')
            if (dayDate < dayFor12) {
                this.yearMonthDay = beforeYesterdayTime
            } else {
                this.yearMonthDay = yesterdayTime
            }
        },
        getDay(num, str) {
            let today = new Date();
            let nowTime = today.getTime();
            let ms = 24 * 3600 * 1000 * num;
            today.setTime(parseInt(nowTime + ms));
            let oYear = today.getFullYear();
            let oMoth = (today.getMonth() + 1).toString();
            if (oMoth.length <= 1) oMoth = '0' + oMoth;
            let oDay = today.getDate().toString();
            if (oDay.length <= 1) oDay = '0' + oDay;
            return oYear + str + oMoth + str + oDay;
        },
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页