Moment.js startOf 返回一天的结束时间

Bla*_*ell 2 node.js express momentjs

我通过查询字符串传递以下日期:2020-09-23

我试图找出为什么上面带有“不起作用”注释的下面的代码不起作用。

// If figure here I should only have to convert to a moment once
const momentDate = moment.utc(req.query.dateTime);

// Doesn't work
const startOfDay = momentDate.startOf('day');
const endOfDay = momentDate.endOf('day');
Run Code Online (Sandbox Code Playgroud)

这就是我得到的:
console.log(startOfDay) = Moment<2020-09-23T23:59:59Z>
console.log(endOfDay) = Moment<2020-09-23T23:59:59Z>

// Works (when I directly pass in the query string param)
const startOfDay = moment.utc(req.query.dateTime).startOf('day');
const endOfDay = moment.utc(req.query.dateTime).endOf('day');
Run Code Online (Sandbox Code Playgroud)

console.log(startOfDay) = 时刻<2020-09-23T00:00:00Z>
console.log(endOfDay) = 时刻<2020-09-23T23:59:59Z>

hgb*_*123 9

您正在对同一个对象执行相同的引用,因此更安全的方法是通过使用方法momentDate克隆该对象来处理该对象的副本momentDateclone()

const momentDate = moment.utc(new Date())

const startOfDay = momentDate.clone().startOf("day")
const endOfDay = momentDate.clone().endOf("day")

console.log(startOfDay)
console.log(endOfDay)
Run Code Online (Sandbox Code Playgroud)