Search code examples
javascriptstringdatelocaledate-format

Convert date format into MM/DD/YYYY


I have dates that are outputted in this format:

Thursday, October 11, 2018

I would need to convert it into

10/11/2018

but first I'm struggling with getting rid of the day of the week (Thursday). Trying to look at other posts but cannot find something similar. Thanks much in adnvace


Solution

  • You need to use Date#toLocaleDateString() method.

    Your code will be like this:

    var str = "Thursday, October 11, 2018";
    let d = new Date(str);
    console.log(d.toLocaleDateString("en-US"))

    Note:

    To get 10/11/2018 from the string October 11, 2018 we need to specify "en-US" as Locale parameter of toLocaleDateString() method so we get the appropriate output, otherwise if you use it without a locale, it may return a wrong output if your time zone is different.