生活随笔
收集整理的這篇文章主要介紹了
js获取当前时间(昨天、今天、明天)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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 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
;var arr_week
= new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");week
= arr_week
[day
];var time
= "";time
= year
+ "年" + month
+ "月" + date
+ "日" + " " + hour
+ ":" + minu
+ ":" + sec
+ " " + week
;console
.log(time
);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
.prototype
.format = function(fmt
) {var o
= {"M+": this.getMonth() + 1, "d+": this.getDate(), "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,"");
總結
以上是生活随笔為你收集整理的js获取当前时间(昨天、今天、明天)的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。