mcya / JavaScriptExperience

👮 JavaScript Experience for web(JavaScript归类:简单入门+数组+经典循环+字符串+函数+Date日期+简单对象+BOM+DOM) +[ Issues(js实用技巧)]
29 stars 8 forks source link

js 关于 时间转换 #46

Open mcya opened 6 years ago

mcya commented 6 years ago

时间关系

mcya commented 6 years ago

昨天、今天、明天 - 常规式

//昨天的时间
var getYesterday = new Date();
getYesterday.setTime(getYesterday.getTime()-24*60*60*1000);
var s1 = getYesterday.getFullYear()+"-" + (getYesterday.getMonth()+1) + "-" + getYesterday.getDate();
//今天的时间
var getToday = new Date();
getToday.setTime(getToday.getTime());
var s2 = getToday.getFullYear()+"-" + (getToday.getMonth()+1) + "-" + getToday.getDate();
//明天的时间
var getTomorrow = new Date();
getTomorrow.setTime(getTomorrow.getTime()+24*60*60*1000);
var s3 = getTomorrow.getFullYear()+"-" + (getTomorrow.getMonth()+1) + "-" + getTomorrow.getDate();
mcya commented 6 years ago

昨天、今天、明天 - 函数式 - 相对来说比较灵活

// format 格式化函数
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}
var everyDay = new Date();
everyDay.setDate(everyDay.getDate() - 1); // `-1`昨天,`+1`明天,`-30`一个月前
var s1 = everyDay.format("yyyy-MM-dd");