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);.................
Use the Date() constructor to convert a string to a Date object, e.g. const date = new Date('2022-09-24') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.
The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). Only the ISO 8601 format ( YYYY-MM-DDTHH:mm:ss.
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); }
Demo
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?").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With