Oam*_*Psy 7 javascript jquery angularjs angularjs-scope
如果我有一个返回日期的变量,格式为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);
});
Run Code Online (Sandbox Code Playgroud)
基本上,这是在本月增加一个..但我怎么能解释多年,所以如果当前日期是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)
Run Code Online (Sandbox Code Playgroud)
虽然月份增加了,但是这一天显示为01而不是28?
只需从月份参数中减去月数,如果值为负值则不用担心.它将被正确处理.
new Date(2014, 0, 1) // 1st Jan 2014
new Date(2014, -1, 1) // 1st Dec 2013
Run Code Online (Sandbox Code Playgroud)
var myVariable = "28 Aug 2014"
var makeDate = new Date(myVariable);
makeDate = new Date(makeDate.setMonth(makeDate.getMonth() - 1));
Run Code Online (Sandbox Code Playgroud)
更新:
更短的版本:
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());Run Code Online (Sandbox Code Playgroud)
对于所有与日期相关的活动,我建议使用 moment.js 库,当您使用 AngularJS 时,有一个用于此的库:https : //github.com/urish/angular-moment。
查看 moment.js 文档,您会发现它使在 JavaScript 中操作日期变得更加容易:http : //momentjs.com/docs/#/get-set/month/
您将能够轻松解决您面临的问题,例如:
var now = moment('01/01/2014').subtract(1, 'months').format('DD/MM/YYYY');
Run Code Online (Sandbox Code Playgroud)
现在将等于 01/12/2013。
| 归档时间: |
|
| 查看次数: |
27446 次 |
| 最近记录: |