Home >Web Front-end >JS Tutorial >JavaScript implements generating a time list within a specified range
Encountered a scenario where we need to get every day within a specified time range, which satisfies the format "YYYYMMDD". It is a simple function. This article mainly shares with you the JavaScript implementation to generate a time list within the specified range. I hope it can help everyone.
Preparation
Date objects have many methods, the following are used:
new date () generates date objects, You can directly specify the year, month, day, etc., new date(year,month,day)
getFullYear() returns the year in the date object
getMonth() returns the month in the date object (0~ 11), please note that counting starts from 0
getDate() returns the day in the date object, note that counting starts from 1
getTime() returns the milliseconds from January 1, 1970 to the date object Number
Parse the specified range
It is stipulated that the time range should be input according to the yyyy-mm-dd format string, and the start and end can be obtained by splitting The year, month and day of the time, then generate the corresponding date object and get the number of milliseconds
let st = start.split('-'); let et = end.split('-'); let startTime = new Date(st[0],st[1]-1,st[2]).getTime(); let endTime = new Date(et[0],et[1]-1,et[2]).getTime();
Note: The month needs to be subtracted by 1 because it starts from 0
Get every day
How to know which days are within the time range? The above has the number of milliseconds from the start and end time to 1970.1.1. Each day has 24 * 60 * 60 * 1000 milliseconds, so we can calculate each day by the number of milliseconds
for( let i = startTime ; i <= endTime ; ){ res.push(formatTime(i,'')); i += 24 * 60 * 60 * 1000; }
Formatted output
Format the time, add 0 to the single digits, and add the specified separator
function formatTime(time,spliter = '-'){ let date = new Date(time); let year = date.getFullYear(); let month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1); let day = date.getDate() >= 10 ? date.getDate() : '0' + date.getDate(); return `${year}${spliter}${month}${spliter}${day} }
Verification
The above is the detailed content of JavaScript implements generating a time list within a specified range. For more information, please follow other related articles on the PHP Chinese website!