Data Operation 日期操做


  • Validate Date

Try convert your Date with 「new Date()」 method which will return 「Invalid Date」 if your Date is not validjavascript

let date = '2019-2-29'; 
let isValid = (new Date(date).toString().toLowerCase() === 'invalid date');
console.log(isValid);  // false 複製代碼


  • DateAdd: Date + Integer = newDate

Add days: Date.setDate ( Date.getDate() +/- n);java

Add months: Date.setMonth ( Date.getMonth () +/- n);markdown

Add Years: Date.setMonth ( Date.getMonth() +/- n * 12);spa

// to add days / months / minus to today
var newDate;
var today = new Date();
if (today.toString().toLowerCase() !== 'invalid date') {
    newDate = new Date(today.setDate(today.getDate() + 40)); // add 40 days to today 
    console.log('add 40 days: ', newDate);    

    newDate = new Date(today.setMonth(today.getMonth() + 13)); // add 13 months 
    console.log('add 13 months: ', newDate);    

    newDate = new Date(today.setMonth(today.getMonth() - 5 * 12));  // minus 5 months 
    console.log('minus 5 years: ', newDate);
}複製代碼
  • Datediff: (date1 - date2) = days / hours / minus / seconds
var date1= new Date();
var date2 = new Date('2019-10-01');
console.log('date1: ', date1); // date1: 2020-01-24T05:34:00.863Z
console.log('date2: ', date2); // date2: 2019-10-01T00:00:00.000Z


date1.setMilliseconds(date1.getMilliseconds());  // convert to milliseconds and then save in date1
date2.setMilliseconds(date2.getMilliseconds());  // convert to milliseconds and then save in date2
console.log('After convert to milliseconds: ');
console.log('date1: '+ date1);  // date1: Fri Jan 24 2020 13:34:00 GMT+0800 (China Standard Time)
console.log('date2: '+ date2);  // date2: Tue Oct 01 2019 08:00:00 GMT+0800 (China Standard Time)


var gap = date1 - date2; // gap: 9956040863 ms
console.log('gap: '+ gap + ' ms'); // gap: 9956040863 ms 
console.log('gap: '+ gap/1000/60/60/24 + ' days'); // gap: 115.23195443287035 days複製代碼
相關文章
相關標籤/搜索