如何不使用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
相关产品推荐
相关产品推荐

