Javascript Angularjs 下一天和前一天,年,月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25719572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:44:43  来源:igfitidea点击:

Angularjs next and previous day,year,month

javascriptangularjsdatefilter

提问by itsme

Using the Angular date $filteractually i can get the current day, year and month.

使用 Angular 日期$filter实际上我可以获得当前的day, year and month.

But, how can i get the next and previous day, year, month?

但是,我怎样才能得到下一个和上一个day, year, month

This is the code i wrote but i dont know where to start with

这是我写的代码,但我不知道从哪里开始

$scope.month = $filter('date')(date, 'MMMM');//December-November like
$scope.day = $filter('date')(date, 'dd'); //01-31 like
$scope.year = $filter('date')(date,'yyyy');//2014 like

$scope.nextYear = Number($scope.year) + 1;
$scope.prevYear = Number($scope.year) - 1;
$scope.nextDay = ?
etc...

Do you have any idea?

你有什么主意吗?

回答by Wawy

You could do it like this, angular date $filter doesn't offer you any easier way of doing it, it just formats a date in a custom desired format.

您可以这样做,角度日期 $filter 不会为您提供任何更简单的方法,它只是以自定义所需的格式格式化日期。

Day:

日:

var myDate = new Date();

var previousDay = new Date(myDate);

previousDay.setDate(myDate.getDate()-1);

var nextDay = new Date(myDate);

nextDay.setDate(myDate.getDate()+1);

Month:

月:

var previousMonth = new Date(myDate);

previousMonth.setMonth(myDate.getMonth()-1);

var nextMonth = new Date(myDate);

nextMonth.setMonth(myDate.getMonth()+1);

Year:

年:

var previousYear = new Date(myDate);

previousYear.setYear(myDate.getFullYear()-1);

var nextYear = new Date(myDate);

nextYear.setYear(myDate.getFullYear()+1);

$scope.month = $filter('date')(myDate, 'MMMM');//December-November like
$scope.day = $filter('date')(myDate, 'dd'); //01-31 like
$scope.year = $filter('date')(myDate,'yyyy');//2014 like

$scope.nextDay = $filter('date')(nexyDay, 'dd');
$scope.prevDay = $filter('date')(previousDay, 'dd');
$scope.nextMonth = $filter('date')(nextMonth, 'MMMM')
$scope.prevMonth = $filter('date')(previousMonth, 'MMMM')
$scope.nextYear = $filter('date')(nextYear,'yyyy');
$scope.prevYear = $filter('date')(previousYear,'yyyy');

If you are going to do this a lot, I suggest you create a service to implement this logic.

如果你打算经常这样做,我建议你创建一个服务来实现这个逻辑。