You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用moment.js获取当月第一天的日期?

不使用Moment.js获取当月第一天的毫秒时间戳

原Moment.js代码的作用是获取当前月份第一天00:00:00的毫秒级时间戳:

const startOfMonth = moment().startOf("month").format("x");

用原生JavaScript可以这样实现:

// 获取当前日期
const now = new Date();
// 构造当月第一天0点的Date对象
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0);
// 转换为毫秒时间戳
const timestamp = startOfMonth.getTime();
console.log(timestamp); // 输出类似1661961600000

代码说明

  • new Date(now.getFullYear(), now.getMonth(), 1, 0, 0, 0, 0):通过指定年份、月份、日期为1,同时将时分秒毫秒设为0,直接创建出当月第一天的零点时间对象
  • getTime():将Date对象转换为毫秒级时间戳,和Moment.js的format("x")效果完全一致

如果需要更简洁的写法,可以合并为一行:

const startOfMonthTimestamp = new Date(new Date().getFullYear(), new Date().getMonth(), 1).getTime();

内容的提问来源于stack exchange,提问作者cypher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:46:58