简体   繁体   English

获取本月的第一天和最后一天

[英]get the first and last day of the month

this has been answered here however maybe something has changed as that no longer works.这已经在这里得到了回答但是也许有些东西已经改变了,因为它不再起作用了。

 function firstAndLast() { const startDate = new Date(2020, 8, 1); const endDate = new Date(2020, startDate.getMonth() + 1, 0) console.log('startDate', startDate) // <-- 2020-08-31T22:00:00.000Z console.log('endDate', endDate) // <-- 2020-09-29T22:00:00.000Z } firstAndLast();

as the docs say the parameters are new Date(YYYY, MM, DD, hh, mm, ss, ms)正如文档所说,参数是new Date(YYYY, MM, DD, hh, mm, ss, ms)

I am entering the year 2020 the month august (note this is node not browser) and day 1 the first of the month.我将进入2020 august月(请注意,这是节点而不是浏览器)和本月第一天的第1天。 What is going on here?这里发生了什么?

You have to consider the Timezone offset.您必须考虑时区偏移。 https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/getTimezoneOffset https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/getTimezoneOffset

 function firstAndLast() { const offset = new Date().getTimezoneOffset() / 60 const startDate = new Date(2020, 8, 1, 0-offset); const endDate = new Date(2020, startDate.getMonth() + 1, 0, 0-offset) console.log('startDate', startDate) // <-- 2020-08-31T22:00:00.000Z console.log('endDate', endDate) // <-- 2020-09-29T22:00:00.000Z } firstAndLast();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM