This article mainly introduces a detailed explanation of the idea of generating a time list within a specified range using JavaScript. Friends who need it can refer to it.
When you encounter a scenario, you need to get every day within the specified time range that meets the format." YYYYMMDD", simple function, simple idea
Preparation
The date object has many methods, the following are used:
new date () generates a date object, 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 (0~11) in the date object, please note that counting starts from 0
getDate() Returns the day in the date object, please note that counting starts from 1
getTime() returns 1970 The number of milliseconds from January 1st to the date object
Parse the specified range
## Specifies that the time should be entered according to the yyyy-mm-dd format string Range, split 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 millisecondslet 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();
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 millisecondsfor( let i = startTime ; i <= endTime ; ){ res.push(formatTime(i,'')); i += 24 * 60 * 60 * 1000; }
Formatted output
Format the time, fill in the single digits with 0, and add the specified separatorfunction 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} }
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Related articles:
React ajax java implements uploading images and previewing functions (graphic tutorial)
AngularJS tab bar implementation and mvc Small case (graphic tutorial)
Example of file upload with progress bar effect based on fileUpload
The above is the detailed content of JavaScript generates a time list within a specified range. For more information, please follow other related articles on the PHP Chinese website!