AngularJS/javascript将日期String转换为日期对象

ali*_*iaz 26 javascript date angularjs

我坚持一个问题,并希望得到任何帮助.我已经阅读了很多讨论,但它们似乎对我不起作用.

//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
Run Code Online (Sandbox Code Playgroud)

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

例如:

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);.................
Run Code Online (Sandbox Code Playgroud)

Jor*_*ego 39

试试这个

HTML

<div ng-controller="MyCtrl">
  Hello, {{newDate | date:'MM/dd/yyyy'}}!
</div>
Run Code Online (Sandbox Code Playgroud)

JS

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

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

    $scope.newDate =new Date(collectionDate);
}
Run Code Online (Sandbox Code Playgroud)

演示


Gar*_*ary 9

我知道这是上面的答案,但我的观点是,我认为所有你需要的是

new Date(collectionDate);
Run Code Online (Sandbox Code Playgroud)

如果您的目标是将日期字符串转换为日期(根据OP"如何将其转换为日期对象?").


ali*_*iaz 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
Run Code Online (Sandbox Code Playgroud)

我最终将日期格式化为指令上的所需模式,如下所示.

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);
Run Code Online (Sandbox Code Playgroud)

这给了我在图表x轴上的日期格式为dd/MM/yyyy(26/04/2002).


bar*_*acı 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");
Run Code Online (Sandbox Code Playgroud)
<!--HTML-->
<!-- First Solution -->
{{myDate  | date:'M/d/yyyy HH:mm:ss'}}
<!-- or -->
{{myDate  | date:'medium'}}

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

<!-- Third Solution -->
{{myDate}}
Run Code Online (Sandbox Code Playgroud)