Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

javascript - 循环遍历daterange中的月份以获得第一个和最后一个日期(Loop through months in daterange get first and last date)

Im building a filter in node.js and i need to loop through months in a given daterange and get the first and last days of said month(我在node.js中构建了一个过滤器,我需要在给定的日期范围内循环浏览几个月,并获取所述月份的第一天和最后几天)

every attempt i make at this after the first few months the dates start getting off(在开始的几个月之后,我为此所做的每一次尝试都会开始) Example of results looping through 1 year(结果循环1年的示例) 2019-01-01 2019-01-31 2019-02-01 2019-02-28 2019-03-01 2019-03-31 2019-03-31 2019-04-29 2019-04-30 2019-05-30 2019-05-31 2019-06-29 2019-06-30 2019-07-30 2019-07-31 2019-08-30 2019-08-31 2019-09-29 2019-09-30 2019-10-31 2019-11-01 2019-11-30 2019-12-01 2019-12-31 by the end it seems to get back the dates(到最后似乎又回到了日期) Any ideas?(有任何想法吗?)   ask by Avi Teller translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They go off because of day lights saving time.(由于日光节约时间,它们熄灭了。)

Just pass in the hour as well when you create the date.(创建日期时也只需输入小时。) for(let a=0;a<12;a++) { let year = new Date().getFullYear() let firstDay = new Date(Date.UTC(year, a , 1)); let lastDay = new Date(Date.UTC(year, a + 1, 0)); document.body.innerHTML += `<div>${firstDay.toISOString().substring(0, 10)} - ${lastDay.toISOString().substring(0, 10)}</div>`; } Working Example(工作实例) Output(输出量) 2019-01-01 - 2019-01-31 2019-02-01 - 2019-02-28 2019-03-01 - 2019-03-31 2019-04-01 - 2019-04-30 2019-05-01 - 2019-05-31 2019-06-01 - 2019-06-30 2019-07-01 - 2019-07-31 2019-08-01 - 2019-08-31 2019-09-01 - 2019-09-30 2019-10-01 - 2019-10-31 2019-11-01 - 2019-11-30 2019-12-01 - 2019-12-31 **Update(**更新) As per RobG suggestion below.(根据下面的RobG建议。) Edited to remove timezone offsets altogether.(编辑以完全删除时区偏移。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...