JavaScript:获取第一个月前 6 个月的日期的最简单方法

JavaScript: simplest way to get the date of the month 6 months prior on the first?

本文关键字:日期 最简单 方法 获取 第一个 JavaScript      更新时间:2023-09-26

所以如果今天是 2010 年 4 月 12 日,它应该返回 2009 年 10 月 1 日

我用谷歌搜索过的一些可能的解决方案似乎过于复杂,有什么建议吗?

您可以使用

两个日期

var date = new Date(2010, 3, 12);
var date6MonthsAgo = new Date(date);
date6MonthsAgo.setMonth(date.getMonth() - 6);
// and to set it to the first date of the month
date6MonthsAgo.setDate(date.getDate() - date.getDate() + 1);

moment.js 是一个很棒的 JavaScript 库,用于显示和操作日期/时间

http://momentjs.com/

在这种情况下,您将使用: var date = moment().subtract(6, 'months').toString();

JSFiddle

https://jsfiddle.net/aadoy9qo/