Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS/javascript converting a date String to date object

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);................. 
like image 819
aliaz Avatar asked Jul 30 '14 02:07

aliaz


People also ask

How do you convert a string to a date in JavaScript?

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.

Is date a string in JS?

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.


2 Answers

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

like image 127
Jorge Casariego Avatar answered Sep 29 '22 15:09

Jorge Casariego


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?").

like image 43
Gary Avatar answered Sep 29 '22 16:09

Gary