-2

Convert date string in to a specific date format in JavaScript.

I am trying to get this output. Here I will give date format dynamically. It should converted to date object. Here dateString is a string.

var dateString = '03/04/2019';
var format = 'dd/mm/yy';
var dateObject = foramtDate(dateString , foramt)
ZUBAIR V
  • 76
  • 6
  • Here links .. I think this will help you well. https://stackoverflow.com/questions/3552461/how-to-format-a-javascript-date – Miks Alibo Apr 03 '19 at 07:26
  • This might help : https://stackoverflow.com/a/1056730/5284695 – Aakash Martand Apr 03 '19 at 07:28
  • I checked above answers. There date object is formatting to a specific format. Here I have to format date string to date. – ZUBAIR V Apr 03 '19 at 07:33
  • Try MomentJS : https://momentjs.com/ – Aakash Martand Apr 03 '19 at 07:35
  • @Zubair V in the question you specifically asked about converting the date from one format to another. Now in your comment you say you just want to make it into a Date object? Please be clear about what you want. Date objects don't have a particular format, formatting only takes place when you convert the date back into a string. If you just want to _parse_ the string into a Date object you can easily Google that, it has been asked 1000 times. – ADyson Apr 03 '19 at 07:46
  • 1
    Perhaps it's just a case of using the wrong word - if you convert a string to a date object, that is _parsing_. If you convert an object back to a string that is _formatting_ . Make sure you search for, and ask about, the correct process. – ADyson Apr 03 '19 at 07:48

1 Answers1

1

This is what I'm using:

// convert string with format 'dd/mm/yy' to Date object
function stringToDate(dateStr) {
    const [day, month, year] = dateStr.split("/");
    return new Date(year, month - 1, day);
};

It's only for one specific format.

UPDATE:

The above script will not work in IE. It uses array destruction which is not supported by the browser. More info here

vixero
  • 514
  • 1
  • 9
  • 21