Watt
Watt

Reputation: 3164

How to parse date time in JavaScript

I have Date in this format mm/dd/yy example: 04/11/13 and time in the format HH:MM:SS example: 17:02:30

I have to parse above two values and put in a variable dateTime with following format

YYYY-MM-DDTHH:MM:SSS

2013-04-11T17:02:30.000

What is best way to do it in AngularJS or in Javascript. I also need to verify the user input and make sure it is a valid mm/dd/yy date and a valid HH:MM:SS time

I know there are tons of duplicate/similar questions but I couldn't find one which answers above, please let me know if you found one.

Upvotes: 5

Views: 17050

Answers (2)

frosty
frosty

Reputation: 21762

The best way to do this in AngularJS is with a filter. You bind to the dateTime, and then filter it with the date filter.

<span>{{myDate | date:yyyy-MM-ddThh:mm:sss}}</span>

Or in your controller you say:

$filter('date')(date[, format])

Here is more info: http://docs.angularjs.org/api/ng.filter:date

Upvotes: -1

Oliver
Oliver

Reputation: 509

You don't need an external library to do this. See this doc link for the forms of date that JavaScript can process normally.

For a specific solution to your question:

var date = new Date("04/11/13" + " " + "17:02:30");
date.toISOString();
>> "2013-04-11T21:02:30.000Z"

See this MDN page for more info on the Date object.

Upvotes: 8

Related Questions