简体   繁体   English

从日期字符串获取月份?

[英]Get month from date string?

I know that I can get the month from a date object using: 我知道我可以使用日期对象获取月份:

var d = new Date();
var n = d.getMonth();

But in my code I have a $scope.start property that seems to not be a date object. 但在我的代码中,我有一个$scope.start属性,似乎不是日期对象。 It is: 它是:

2016-02-17T14:39:00Z

How can I extract the month from $scope.start ? 如何从$scope.start提取月份?

This will give you a month as a number from 0 to 11 这将给你一个月的数字从0到11

 var date = new Date('2016-12-17T14:39:00Z');
 var month = date.getMonth();
$scope.start = new Date('2016-02-17T14:39:00Z');
$scope.startMonth= $scope.start.getMonth() + 1;

http://jsfiddle.net/ms403Ly8/57/ http://jsfiddle.net/ms403Ly8/57/

May be this will help you pass the date string to Date() constructor. 可能这将帮助您将日期字符串传递给Date()构造函数。

now the date object is of date contain in string and if u print month or alert it will give u month-1 value. 现在日期对象的日期包含在字符串中,如果你打印月份或警告,它将给出你的月份1值。

here is code. 这是代码。 please have a look on it 请看看它

 var d = new Date('2016-02-17T14:39:00Z'); var n = d.getMonth(); alert(n); var d = new Date('2016-03-17T14:39:00Z'); var n = d.getMonth(); alert(n) 

May I recommend the following approach 我可以推荐以下方法

var n = new Date($scope.start);
var month = n.getMonth();

You need to convert the string to a date object. 您需要将字符串转换为日期对象。

You should be able to do it by using split ! 你应该可以通过使用拆分来做到这一点! Try something like this 尝试这样的事情

$scope.start = "2016-02-17T14:39:00Z";
{{start.split('-')[0]}}

now you will get, "Month" while you try "{{start.split('-')[1]}}"

But Normally 0 means jan, 1 -> feb, 2-> mar,... so only we did some +1, -1... 但通常0表示jan,1 - > feb,2-> mar,...所以只有我们做了一些+1,-1 ......

 <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Get Previous next Day, Month, Year Month Time in Angularjs</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script> <script type="text/javascript"> var app = angular.module('sampleapp', []) app.controller('samplecontrol', function ($scope) { var previousMonth = new Date() $scope.pmonth = previousMonth.getMonth(); var currentMonth = new Date() $scope.cmonth = currentMonth.getMonth() + 1; var nextMonth = new Date() $scope.nmonth = nextMonth.getMonth() + 2; }); </script> </head> <body data-ng-app="sampleapp" data-ng-controller="samplecontrol"> <form id="form1"> <div> Previous Month:<b> {{pmonth }}</b><br /> Current Month:<b> {{cmonth }}</b><br /> Next Month:<b> {{nmonth }}</b><br /> </div> </form> </body> </html> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM