หลายครั้งที่เราสามารถใช้วิธีการในตัวของวัตถุวันที่ใน JavaScript เพื่อจัดรูปแบบพวกเขาเช่น:
การคัดลอกรหัสมีดังนี้: var d = วันที่ใหม่ ();
console.log (d);
console.log (D.Todatestring ());
console.log (d.togmtstring ());
console.log (d.toisostring ());
console.log (d.tojson ());
console.log (d.tolocaleDateString ());
console.log (d.tolocalestring ());
console.log (d.tolocaletimestring ());
console.log (D.ToString ());
console.log (d.totimestring ());
console.log (d.toutcstring ());
หากวิธีการข้างต้นไม่สามารถตอบสนองความต้องการของเราได้คุณสามารถปรับแต่งฟังก์ชั่นเพื่อจัดรูปแบบเวลาเช่น:
การคัดลอกรหัสมีดังนี้:
date.prototype.format = function (รูปแบบ) {
var date = {
"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 ()
-
ถ้า (/(y+)/i.test(format)) {
format = format.replace (regexp. $ 1, (this.getlyear () + '') .substr (4 - regexp. $ 1. ความยาว));
-
สำหรับ (var k ในวันที่) {
if (ใหม่ regexp ("(" + k + ")"). ทดสอบ (รูปแบบ)) {
format = format.replace (regexp. $ 1, regexp. $ 1. ความยาว == 1
วันที่ [k]: ("00" + วันที่ [k]) substr ("" + วันที่ [k]).
-
-
รูปแบบการส่งคืน;
-
var d = วันที่ใหม่ (). รูปแบบ ('yyyy-mm-dd');
console.log (d);