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:
eg:
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 question is related to
javascript
angularjs
date
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);
This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.
try this
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);
}
I know this is in the above answers, but my point is that I think all you need is
new Date(collectionDate);
if your goal is to convert a date string into a date (as per the OP "How do I convert it to a date object?").
//JS_x000D_
//First Solution_x000D_
moment(myDate)_x000D_
_x000D_
//Second Solution_x000D_
moment(myDate).format('YYYY-MM-DD HH:mm:ss')_x000D_
//or_x000D_
moment(myDate).format('YYYY-MM-DD')_x000D_
_x000D_
//Third Solution_x000D_
myDate = $filter('date')(myDate, "dd/MM/yyyy");
_x000D_
<!--HTML-->_x000D_
<!-- First Solution -->_x000D_
{{myDate | date:'M/d/yyyy HH:mm:ss'}}_x000D_
<!-- or -->_x000D_
{{myDate | date:'medium'}}_x000D_
_x000D_
<!-- Second Solution -->_x000D_
{{myDate}}_x000D_
_x000D_
<!-- Third Solution -->_x000D_
{{myDate}}
_x000D_
Source: Stackoverflow.com