Addition and subtraction of specified dates and days based on the Date type in JavaScript

One line of code, easy to copy.

// 生日天数倒计时
var countDayToNextBirthday = function (year, month, day) {
    
     return Number.parseInt((new Date(year, month - 1, day) - new Date()) / 1000 / 60 / 60 / 24); };
console.log("从今天起到下次生日还剩的天数:", countDayToNextBirthday(2024, 2, 21));

insert image description here

Intro

Just now it suddenly occurred to me how long it will be before my 27th birthday.
In his late thirties, he has accomplished nothing.

The following encapsulates some methods based on the Date object in JavaScript.

basic method

Constructor – how to initialize a Date object?

new Date()
// Mon Jun 19 2023 23:32:33 GMT+0800 (中国标准时间)
new Date().toLocaleString()
// '2023/6/19 23:32:38'
new Date(2024, 2-1, 21).toLocaleString()
// '2024/2/21 00:00:00'
new Date("02 21, 2024").toLocaleString()
// '2024/2/21 00:00:00'

insert image description here
Only the above three are mentioned here.

For more usage methods of Date's construction method, see: https://blog.csdn.net/Aiyining/article/details/87925443
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date

Date object addition and subtraction of days

Today is 2023-06-19, what is the date after 100 days?

a = new Date()
// Mon Jun 19 2023 23:36:53 GMT+0800 (中国标准时间)
a.toLocaleString()
// '2023/6/19 23:36:53'
a.setDate(a.getDate() + 100);
// 1695829013049
a.toLocaleString()
// '2023/9/27 23:36:53'

insert image description here

Reference: https://www.cnblogs.com/poterliu/p/10220135.html
insert image description here

【Tool method package】

// 获取指定年月日下的日期
function getSpecificDate(year, month, day) {
    
    
    return new Date(year, month - 1, day);
}

// 获取指定日期前/后n多天的日期,days可为正可为负。
function dateAddDays(date, days) {
    
    
    var newDate = new Date(date);   // 复制一个Date对象
    newDate.setDate(date.getDate() + days);
    return newDate;
}

// 获取两个指定日期之间的天数
function getDaysBetween(startDate, endDate) {
    
    
    return (endDate - startDate) / 1000 / 60 / 60 / 24;
}

// 打印某个日期
function showDate(date) {
    
    
    console.log(date.toLocaleString());
}

var birthday = getSpecificDate(2024, 2, 21);
showDate(birthday);

var minus100 = dateAddDays(birthday, -100);
showDate(minus100);
var minus200 = dateAddDays(birthday, -200);
showDate(minus200);

var daysTo27Birthday = getDaysBetween(new Date(), birthday);
console.log(daysTo27Birthday);

Execute it in the console:

insert image description here

at last

I always feel that time passes quickly, I grow older year by year, nothing is done, and nothing is solved.
After doing the math today, I still have 246 days to use it before my 27th birthday.
Can do a lot.
come on.

The opportunity to experience each day is priceless.

Guess you like

Origin blog.csdn.net/wuyujin1997/article/details/131297327