How to convert string into date format (yyyy-MM-dd) using Javascript?


(this.is.sparta) #1

i want to convert a string of date of format (yyyy-MM-dd) into a date object using javascript, i used the code below but it doesn’t work:

var date_input = new Date($("#date_input").val());
var date_format = new Date(date_input).toDateString("yyyy-MM-dd");

any help will be appreciated!


(Yassine) #2

please read the Javascript documentation, you are using the toDateString() method wrong way.


(isoftech) #3

I don’t think Date.toDateString() function takes any parameters,

Read this documentation : Date.prototype.toDateString().

you have two options:

  1. Use some external Javascript libraries for Date formatting like moment.js.

  2. Or in your case use some manual formatting:
    As you only need a simple date format(yyyy-MM-dd), so use this code below.

    var date_input = new Date($("#date_input").val());
    var day = date_input.getDay();
    var month = date_input.getMonth() + 1;
    var year = date_input.getFullYear();
    var yyyy_MM_dd = year + “-” + month + “-” + day; // That’s your formatted date.