JavaScript:年月日時分秒設置

/* 獲取四位年份 */
function year(d){return d?d.getFullYear():(new Date()).getFullYear();};  //函數法獲取年份
Date.prototype.__defineGetter__('year', function() {return this.getFullYear();});  //prototype法獲取年份
Date.prototype.__defineSetter__('year', function(y) {this.setFullYear(y)});  //prototype法設置年份

/* 獲取月份 */
function month(d){return d?d.getMonth():(new Date()).getMonth();};  //函數法獲取月份
Date.prototype.__defineGetter__('month', function() {return this.getMonth();});  //prototype法獲取月份
Date.prototype.__defineSetter__('month', function(m) {this.getMonth(m)});  //prototype法設置月份

/* 獲取日期 */
function date(d){return d?d.getDate():(new Date()).getDate();};  //函數法獲取日期
Date.prototype.__defineGetter__('date', function() {return this.getDate();});  //prototype法獲取日期
Date.prototype.__defineSetter__('date', function(d) {this.getDate(d)});  //prototype法設置日期

/* 獲取曜日 */
function day(d){return d?d.getDay():(new Date()).getDay();};  //函數法獲取曜日
Date.prototype.__defineGetter__('day', function() {return this.getDay();});  //prototype法獲取曜日
Date.prototype.__defineSetter__('day', function(d) {this.getDay(d)});  //prototype法設置曜日

/* 獲取小時 */
function hour(d){return d?d.getHours():(new Date()).getHours();};  //函數法獲取小時
Date.prototype.__defineGetter__('hour', function() {return this.getHours();});  //prototype法獲取小時
Date.prototype.__defineSetter__('hour', function(d) {this.getHours(d)});  //prototype法設置小時

/* 獲取分鐘 */
function minute(d){return d?d.getMinutes():(new Date()).getMinutes();};  //函數法獲取分鐘
Date.prototype.__defineGetter__('minute', function() {return this.getMinutes();});  //prototype法獲取分鐘
Date.prototype.__defineSetter__('minute', function(d) {this.getMinutes(d)});  //prototype法設置分鐘

/* 獲取秒鐘 */
function second(d){return d?d.getSeconds():(new Date()).getSeconds();};  //函數法獲取秒鐘
Date.prototype.__defineGetter__('second', function() {return this.getSeconds();});  //prototype法獲取秒鐘
Date.prototype.__defineSetter__('second', function(d) {this.getSeconds(d)});  //prototype法設置秒鐘

/* 獲取毫秒 */
function millisecond(d){return d?d.getMilliseconds():(new Date()).getMilliseconds();};  //函數法獲取毫秒
Date.prototype.__defineGetter__('millisecond', function() {return this.getMilliseconds();});  //prototype法獲取毫秒
Date.prototype.__defineSetter__('millisecond', function(d) {this.getMilliseconds(d)});  //prototype法設置毫秒

//prototype使用說明

console.log((new Date()).year)    //打印2019
原文地址:https://www.cnblogs.com/mandongpiaoxue/p/10494690.html