本文介绍了AngularJS/javascript 将日期字符串转换为日期对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Im stuck on a problem and would appreciate any help. I have read through lot of the discussions already but they dont seem to work for me.

//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

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

How do I convert it to a date object? The reason I want to do this is because I want to use it in a google charts directive where one of the columns has to be a date. I do not want to have the column type as 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);.................

推荐答案

这是我在控制器上所做的

This is what I did on the controller

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

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

I ended up formatting the date to my desired pattern on the directive as follows.

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) 格式的日期.

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

这篇关于AngularJS/javascript 将日期字符串转换为日期对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 08:55