Javascript如何計算日期時間加減一年一個月一天方法

4 月 20, 2018 | | 0 條留言

js

設置日期時間方法

setFullYear()、setMonth()、setDate()方法用於設置年份、月、日,返回值返回調整過的日期的毫秒表示。

時期返回數字年月日函數

getFullYear() 方法可返回一個表示年份的4 位數字

getMonth() 方法可返回表示月份的數字。返回值是0(一月) 到11(十二月) 之間的一個整數。

getDate() 方法可返回月份的某一天。返回值是1 ~ 31 之間的一個整數。

範例一

var d1 = new Date(2004/02/1); 
var d2 = new Date(d1); 
d2.setFullYear(d2.getFullYear()-1); 
d2.setDate(d2.getDate()-1); 

console.log(d2); 

// Output: Fri Jan 31 2003 00:00:00 GMT+0800 (台北標準時間)

範例二

var myDate = new Date(1/1/1990)
myDate.setMonth(myDate.getMonth() + 1);
myDate.setDate (myDate.getDate() - 1);

console.log(myDate);

// Output: Wed Jan 31 1990 00:00:00 GMT+0800 (台北標準時間)

Javascript個年度的同月同日日期

today = new Date();
year = this.today.getFullYear();
month = this.today.getMonth();
day = this.today.getDate();

//To go 18 years back 18年前同月同日
yearsBack18= new Date(this.year - 18, this.month, this.day);

//To go to same day next year 下一年度同月同日
nextYear= new Date(this.year + 1, this.month, this.day);