AngularJS/Javascript将日期字符串转换为日期对象

26

我遇到了一个问题,希望能得到帮助。我已经阅读了很多讨论,但它们似乎对我没有用。

//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);.................
4个回答

41

试一试

HTML

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

JS

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

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

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

演示


9
我知道上面的答案中已经提到了,但我的观点是,我认为你只需要 这些
new Date(collectionDate);

如果你的目标是将一个日期字符串转换成日期对象(如"如何将其转换为日期对象?"),那么可以使用以下方法:

7

这是我在控制器上所做的

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);

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


5

//JS
//First Solution
moment(myDate)

//Second Solution
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
//or
moment(myDate).format('YYYY-MM-DD')

//Third Solution
myDate = $filter('date')(myDate, "dd/MM/yyyy");
<!--HTML-->
<!-- First Solution -->
{{myDate  | date:'M/d/yyyy HH:mm:ss'}}
<!-- or -->
{{myDate  | date:'medium'}}

<!-- Second Solution -->
{{myDate}}

<!-- Third Solution -->
{{myDate}}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接