How JS compares date sizes
This article mainly introduces the relevant knowledge of "how JS compares date size". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to compare date size in JS" can help you solve the problem.
1. Year-month-day-hour-minute-second
/ / get the current time
Let currentTime = new Date ()
/ / Custom time
Let customTime = "2021-12-23 00:00:00"
/ / replace characters and change them to standard format
CustomTime = customTime.replace ("-", "/")
CustomTime = new Date (Date.parse (customTime))
If (currentTime
< customTime) { console.log(`当前时间小于自定义时间!\n当前时间:${currentTime}\n自定义时间:${customTime}`); } else if (currentTime >CustomTime) {
Console.log (`The current time is greater than the custom time! \ ncurrent time: ${currentTime}\ nCustom time: ${customTime} `)
} else if (currentTime = = customTime) {
Console.log (`current time equals custom time! \ ncurrent time: ${currentTime}\ nCustom time: ${customTime} `)
}
2. Year-month-day
Let date1 = new Date ('2019-03-01')
Let date2 = new Date ('2020-03-01')
If (date1 > date2) {
Console.log (the larger date is date1:\ n$ {date1} `)
} else if (date1
< date2) { console.log(`日期较大的是date2:\n${date2}`); } else { console.log(`date1:${date1}\ndate2:${date2}\n相等`); } 3、时-分-秒 // 1.时分秒转换时间戳 function timeStamp(time) { if (time !== null) { let s = ""; let hour = time.split(":")[0]; let min = time.split(":")[1]; let sec = time.split(":")[2]; s = Number(hour * 3600) + Number(min * 60) + Number(sec); return s; } }; // 2.比较时间 function compareTime(startTime, endTime) { if (timeStamp(endTime) - timeStamp(startTime) >0) {
Console.log ('end time is greater than start time!')
} else if (timeStamp (endTime)-timeStamp (startTime) = = 0) {
Console.log ('end time equals start time')
} else {
Console.log ('end time is less than start time')
}
}
/ / 3. Time to proceed
Let time1 ='00: 00: 00'
Let time2 ='03: 21: 00'
CompareTime (time1, time2)
This is the end of the introduction to "how JS compares date sizes". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.