This time I will bring you JS to generate a time list and output it. What are theprecautions for JS to generate a time list and output it? The following is a practical case, let's take a look.
Encountered a scenario where you need to get every day within the specified time range, satisfying the format "YYYYMMDD", simple function, simple ideaPreparation
DateObjectThere are 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, note that counting starts from 0getDate() Returns the day in the date object. Note that counting starts from 1
getTime() Returns the number of milliseconds from January 1, 1970 to the date objectAnalyze the specified range
It is specified in the yyyy-mm-dd formatlet 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; }
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} }
Otherrelated articles!
Recommended reading:React-native package plug-in swiper usage steps detailed explanation
FIFO/LRU implementation caching algorithm
The above is the detailed content of JS generates a time list and outputs it. For more information, please follow other related articles on the PHP Chinese website!