【问题标题】:Moment.js startOf is returning end of dayMoment.js startOf 正在返回一天结束
【发布时间】:2020-08-25 14:33:24
【问题描述】:

我通过查询字符串传递以下日期: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');

这是我得到的:
console.log(startOfDay) = 时刻
console.log(endOfDay) = Moment

// 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');

console.log(startOfDay) = 时刻
console.log(endOfDay) = Moment

【问题讨论】:

  • 在您的“工作”示例中,您使用的是moment 而不是moment.utc,如果您使用moment.utc,它仍然有效吗?
  • @Rastalamm 是的,抱歉应该放在那里。
  • .startOf.endOf mutate 现有日期(参见例如momentjs.com/docs/#/manipulating/start-of),所以我希望根据您是否有一个或两个时刻会有不同的行为对象。

标签: node.js express momentjs


【解决方案1】:

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

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

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

console.log(startOfDay)
console.log(endOfDay)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-02
    • 2018-07-04
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多