JavaScript generates a time list for the specified range, and javascript generates
In a scenario, you need to get every day within the specified time range, satisfying the format of "YYYYMMDD", simple functions, and simple ideas.
Preparation
The date object has many methods and uses the following:
New date () generates a date object. You can directly specify the year, month, day, and so on. new date (year, month, day)
GetFullYear () returns the year in the date object.
GetMonth () returns the month (0 ~) in the date object ~ 11). Note that it starts from 0.
GetDate () returns the day in the date object. Note that the value starts from 1.
GetTime () returns the number of milliseconds from January 1, January 1, 1970 to date.
Resolution Range
Enter the time range according to the string in yyyy-mm-dd format. split the time to get the year, month, and day of the start and end time, and then generate the corresponding date object to 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 must be reduced by 1 because it starts from 0.
Get every day
How can we know the days in the time range? The number of milliseconds between the start time and the end time is 1000. Each day has 24*60*60 * milliseconds. Therefore, we can calculate the number of milliseconds for each day.
for( let i = startTime ; i <= endTime ; ){ res.push(formatTime(i,'')); i += 24 * 60 * 60 * 1000; }
Format output
Format the time, add 0 to a single digit, and add the specified delimiter.
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}}
Verify
Summary
The above section describes how to use JavaScript to generate a time list for a specified range. I hope it will be helpful to you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!