如果我有一个返回日期的变量,格式为 dd MMM yyyy,即 2014 年 8 月 28 日,我如何获取上个月的日期。
我可以通过以下方式修改月份:
$scope.DateMapping = function (months) {
var myVariable = "28 Aug 2014"
var makeDate = new Date(myVariable);
prev = new Date(makeDate.getFullYear(), makeDate.getMonth()+1, 1);
});
本质上,这是在月份上加一。但是我如何计算年份,所以如果当前日期是 2014 年 12 月 12 日,那么之前的日期是 2013 年 1 月 12 日?
我的应用程序使用 AngularJS 可以使用过滤器。
更新:
var myVariable = "28 Aug 2014"
var makeDate = new Date(myVariable);
var prev = new Date(makeDate.getFullYear(), makeDate.getMonth()+1, makeDate.getMonth());
console.log(myVariable)
console.log(makeDate)
console.log(prev)
Output:
28 Aug 2014
Thu Aug 28 2014 00:00:00 GMT+0100 (GMT Standard Time)
Mon Sep 01 2014 00:00:00 GMT+0100 (GMT Standard Time)
为什么虽然月份增加了,但日期却显示为 01 而不是 28?
最佳答案
var myVariable = "28 Aug 2014"
var makeDate = new Date(myVariable);
makeDate = new Date(makeDate.setMonth(makeDate.getMonth() - 1));
更新:
一个较短的版本:
var myVariable = "28 Aug 2014"
var makeDate = new Date(myVariable);
console.log('Original date: ', makeDate.toString());
makeDate.setMonth(makeDate.getMonth() - 1);
console.log('After subtracting a month: ', makeDate.toString());
更新 2:
如果您不想处理极端情况,只需使用 moment.js。 Date 的原生 JavaScript API 很糟糕。
关于Javascript - 获取上个月的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488043/