【问题标题】:Array of dates prints unexpected dates in moment js日期数组在时刻 js 中打印出意外的日期
【发布时间】:2020-11-11 06:26:31
【问题描述】:
在我的代码 sn-p 中,时刻 js 没有给出预期的结果。
weekStart 设置为本周开始(即 7 月 19 日),weekEnd 设置为本周结束(即 7 月 25 日)。
单独打印时,两者都打印了正确的日期,但是当它从数组中使用时(validRange),weekStart 打印的是 25th Jul 而不是 19th Jul强>。
有什么解决办法吗?可能是什么原因?
const today = moment() // let take today is 22 July 2020
const weekStart = today.startOf('week'); // 19th
console.log(weekStart.toString()); // Sun Jul 19 2020 00:00:00 GMT+0530
const weekEnd = today.endOf('week'); // 25th
console.log(weekEnd.toString()); // Sat Jul 25 2020 23:59:59 GMT+0530
const validRange = [weekStart,weekEnd]; // should be an array
console.log(validRange.map(item =>item.toString())); // ["Sat Jul 25 2020 23:59:59 GMT+0530", "Sat Jul 25 2020 23:59:59 GMT+0530"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
示例输出:
【问题讨论】:
标签:
javascript
node.js
arrays
reactjs
momentjs
【解决方案1】:
startOf 和 endOf 方法修改当前对象。所以你需要为每个weekStart和weekEnd实例化一个对象。
const today = moment() // let take today is 22 July 2020
const weekStart = moment(today).startOf('week'); // 19th
console.log(weekStart.format()); // Sun Jul 19 2020 00:00:00 GMT+0530
const weekEnd = moment(today).endOf('week'); // 25th
console.log(weekEnd.format()); // Sat Jul 25 2020 23:59:59 GMT+0530
const validRange = [weekStart,weekEnd]; // should be an array
console.log(validRange.map(item =>item.format())); // ["Sat Jul 25 2020 23:59:59 GMT+0530", "Sat Jul 25 2020 23:59:59 GMT+0530"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
【解决方案2】:
moment 日期是可变的(请参阅the docs)。这意味着当您执行以下操作时:
const today = moment(); // today = today
const weekStart = today.startOf('week'); // today now equals the start of the week, and
// you've assigned it to a new variable
你想要做的是:
const today = moment(); // today = today
const weekStart = today.clone().startOf('week'); // make a clone of today and then change
// it to the start of the week
【解决方案3】:
当您调用.startOf 或.endOf 时,它会修改today,并返回today。您需要 .clone 获取日期的唯一实例。
const today = moment() // let take today is 22 July 2020
const weekStart = today.clone().startOf('week'); // 19th
console.log(weekStart.toString()); // Sun Jul 19 2020 00:00:00 GMT+0530
const weekEnd = today.clone().endOf('week'); // 25th
console.log(weekEnd.toString()); // Sat Jul 25 2020 23:59:59 GMT+0530
const validRange = [weekStart,weekEnd]; // should be an array
console.log(validRange.map(item =>item.toString())); // ["Sat Jul 25 2020 23:59:59 GMT+0530", "Sat Jul 25 2020 23:59:59 GMT+0530"]
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>