2

Parse a string to a specific date format in JavaScript.

I will give input as a string(date string) and a date format(string). Expecting output as date object.

I searched in stackoverflow and found some questions and answers. I checked How to format a JavaScript date , Where can I find documentation on formatting a date in JavaScript? and Converting a string to a date in JavaScript

But all are explaining about converting or formatting date to string. I am looking for parsing a string to date object.

Here I will give date in string format. That is input data is not a date object. And giving format of date. Date format is giving dynamically. That is sometime it is "MM/DD/YYYY" or 'dd/mm/yy' etc. Expected output is date object.

Example 1

var string1 = '03/04/2019';
var format = 'dd/mm/yy';
var dateObject = parse(string1 , format );

Example 2

var string1 = '10/21/2013';
var format = 'MM/DD/YYYY';
var dateObject = parse(string1 , format );
ZUBAIR V
  • 76
  • 6
  • 6
    I suggest you to use moment.js – Fatih TAN Apr 03 '19 at 11:20
  • Hi! look here https://stackoverflow.com/questions/5619202/converting-a-string-to-a-date-in-javascript – gpasci Apr 03 '19 at 11:21
  • 1
    I can not use external API in my project. Is there any method in JavaScript or JQuery for above requirement. – ZUBAIR V Apr 03 '19 at 11:23
  • You need to provide your own date parsing function. Hence it's almost always a good idea to store dates in ISO8601 notation: `yyyy-mm-ddThh:mm:ss.ffffff` or as a unix timestamp integer. Both of these can natively be parsed by `new Date()` without the need to create a function that breaks up your own date format into the correct parameters to use with `new Date()`. – Shilly Apr 03 '19 at 11:23
  • Durga : I checked your comment. In my case date format always different. It is not helped me. Thanks. – ZUBAIR V Apr 03 '19 at 11:32
  • 1
    If you can't specify the date format at runtime then it's impossible to infer a date from your string. – Reinstate Monica Cellio Apr 03 '19 at 13:20
  • Please look at my answer [here](https://stackoverflow.com/a/55503943/9325419) – jo_va Apr 03 '19 at 20:43

0 Answers0