JS date date object plus and minus calculation days-Kaiqisan

JS date plus and minus calculation days

ヤッハロー, Kaiqisan すうう, 一つふつうの学生プログラマである, following the content of the previous section, this time I will talk about how to modify the content of the time object. There are already overwhelming methods on the Internet. Today, I will write a different method for everyone!

The main tone of the method this time is to use Date.parse to generate the distance (unit: milliseconds) between the current time and 0:00:00 on January 1, 1970, and then obtain the absolute distance between the two times and the initial time. Calculate the relative distance between two times (in milliseconds). After the time difference is obtained, the rest is easy. (Of course, all of this is based on the js Date object, if there is no Date object, it will be uncomfortable)

The following is the reference source code

Calculation time difference

let birth = new Date('2000-08-29 22:05:12')
let nowTime = new Date()
function getDayNum(time, compareTime) {
    
    
    let s = Math.abs(Date.parse(time) - Date.parse(compareTime)) // 取绝对值
	let day = Math.floor(s / 86400000)
	let hour = Math.floor((s % 86400000) / 3600000)
	let min = Math.floor(((s % 86400000) % 3600000) / 60000)
	console.log(`我一共活了${
      
      day}${
      
      hour}小时${
      
      min}分钟,人生苦短,及时行乐。`);
}
getDayNum(birth, nowTime)
// 我一共活了7301天16小时15分钟,人生苦短,及时行乐。

Forward or backward for a certain amount of time

let nowTime = new Date()

function setNowTime(time, changeDay) {
    
     // 只能修改日期
	let res = Date.parse(time) + changeDay * 86400000
	res = new Date(res)
	console.log(res);
}
setNowTime(nowTime, -5) // 往后回退5天

If you want to improve on my method, you can also add the modification time function (hours, minutes, and seconds)

to sum up

In fact, the core of the time object is to use the time in the early morning of January 1, 1970 as a reference, and all times are generated based on it.

Guess you like

Origin blog.csdn.net/qq_33933205/article/details/108239409