5

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.

5
  • creating filter is the best way to do it Commented Jun 7, 2013 at 19:34
  • 2
    Might worth considering moment.js momentjs.com Commented Jun 7, 2013 at 19:36
  • @Ajaybeniwal Can you provide any code example? Commented Jun 7, 2013 at 19:36
  • @mishik, I have looked into momentjs. Isn't that good for manipulating date-time not for this parsing. Can you provide some code example. Commented Jun 7, 2013 at 19:38
  • moment("<your_date>", "<your_date_format>").format("<format_needed>") e.g.: moment("04/11/13 17:02:30", "MM/DD/YY HH:mm:ss").format() The default "format()" seems like what you need. Commented Jun 7, 2013 at 19:42

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1. This is great! BTW, this is for another problem is there a way quick way using the same API to convert the resultant Z zulu time back to user's local time-zone?
Yep! Since when we initially created the Date object we didn't specify the time offset, JavaScript automatically uses the local user's timezone. To get the time in the user's local time we could do something like date.toLocaleTimeString("ca-8601") which will return "17:02:30".
Additionally you can specify the timezone in the date string e.g. new Date("2014 Jul 21 GMT+0530 07:51:00")
-1

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

1 Comment

Although this function is very useful, it is not relevant for this question which is about parsing the date.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.