AngularJS/javascript将一个日期字符串转换为日期对象

我在一个问题上卡住了,希望得到任何帮助。我已经阅读了很多讨论,但它们似乎对我不起作用。

//I have a date as a string which I want to get to a date format of dd/MM/yyyy
var collectionDate = '2002-04-26T09:00:00'; 

//used angularjs date filter to format the date to dd/MM/yyyy
collectionDate = $filter('date')(collectionDate, 'dd/MM/yyyy'); //This outputs 26/04/2002 as a string

我如何将其转换为一个日期对象?我想这样做的原因是,我想在谷歌图表指令中使用它,其中一列必须是日期。我不希望列的类型是字符串:

比如说

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);.................

试试这个

html

<div ng-controller="MyCtrl">
  Hello, {{newDate | date:'MM/dd/yyyy'}}!
</div>

JS

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var collectionDate = '2002-04-26T09:00:00'; 

    $scope.newDate =new Date(collectionDate);
}

[演示][1]

评论(0)
解决办法

这是我在控制器上做的事情

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

我最终在指令上将日期格式化为我想要的模式,如下所示。

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

这让我在图表的X轴上得到了日期是dd/MM/yyyy的格式(26/04/2002)。

评论(0)