Javascript - 获取上个月的日期 [英] Javascript - Get Previous Months Date

查看:369
本文介绍了Javascript - 获取上个月的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个返回日期的变量,格式为dd MMM yyyy,那么2014年8月28日,我怎样才能得到上个月的日期。

If i have a variable that returns a date, in the format of dd MMM yyyy, so 28 Aug 2014, how can i get the date of the previous month.

我可以通过以下方式修改月份:

I can modify the month via:

$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日?

Essentially, this is adding one to the Month.. But how can i account for years, so if the current date is 12 Dec 2014, the previous would be 12 Jan 2013?

我的应用程序使用AngularJS可以使用过滤器。

My application is using AngularJS can make use of filters.

更新:

    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?

How comes although the month has incremented, the day is showing as 01 instead of 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());

这篇关于Javascript - 获取上个月的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆