- js获取当前时间(昨天、今天、明天)
//昨天的时间var day1 = new Date();day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);var s1 =day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate();console.log(day1, s1); //今天的时间var day2 = new Date();day2.setTime(day2.getTime());var s2 =day2.getFullYear() + "-" + (day2.getMonth() + 1) + "-" + day2.getDate();console.log(day2, s2);//明天的时间var day3 = new Date();day3.setTime(day3.getTime() + 24 * 60 * 60 * 1000);var s3 =day3.getFullYear() + "-" + (day3.getMonth() + 1) + "-" + day3.getDate();console.log(day3, s3);
打印结果
- 下面是具体到时分秒的获取方法
function writeCurrentDate() {var now = new Date();var year = now.getFullYear(); //得到年份var month = now.getMonth();//得到月份var date = now.getDate();//得到日期var day = now.getDay();//得到周几var hour = now.getHours();//得到小时var minu = now.getMinutes();//得到分钟var sec = now.getSeconds();//得到秒// var MS = now.getMilliseconds();//获取毫秒var week;month = month + 1;if (month < 10) month = "0" + month;if (date < 10) date = "0" + date;if (hour < 10) hour = "0" + hour;if (minu < 10) minu = "0" + minu;if (sec < 10) sec = "0" + sec;// if(MS < 100)MS = "0" + MS;var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");week = arr_week[day];var time = "";time = year + "年" + month + "月" + date + "日" + " " + hour + ":" + minu + ":" + sec + " " + week;console.log(time);//设置得到当前日期的函数的执行间隔时间,每1000毫秒刷新一次。var timer = setTimeout("writeCurrentDate()", 1000);}writeCurrentDate()
打印结果
- 2020.10.10更新
今天又发现了一种简单的方法:可以直接对年月日时分秒进行操作,假如今天2017-10-10 那么所得昨天为 2017-10-09
//昨天的时间var day1 = new Date();day1.setDate(day1.getDate() - 1);var s1 = day1.format("yyyy-MM-dd");console.log(day1, s1);//前天的时间var day2 = new Date();day2.setDate(day2.getDate() - 2);var s2 = day2.format("yyyy-MM-dd");console.log(day2, s2);
打印结果
其中,format函数为扩展函数
/***对Date的扩展,将 Date 转化为指定格式的String*月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,*年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)*例子:*(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423*(new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18*/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;};
- 页面日期 2020-10-10 变 20201010 “2020-10-10”.replace(/-/g,"");