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

查看:35
本文介绍了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());

如果您不想处理极端情况,请使用 moment.js.用于 Date 的原生 JavaScript API 很糟糕.

If you don't want to deal with corner cases just use moment.js. Native JavaScript API for Date is bad.

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

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