Stopbyte

Best way to convert string to date in Javascript?

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!

4 Likes

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

2 Likes

Date.toDateString() function does not take any parameters,

According to this documentation : Date.prototype.toDateString().

The toDateString() method returns the date portion of a Date object in English in the following format separated by spaces:

  1. First three letters of the week day name
  2. First three letters of the month name
  3. Two digit day of the month, padded on the left a zero if necessary
  4. Four digit year (at least), padded on the left with zeros if necessary

E.g. “Thu Jan 01 1970”.

You have two easy options to convert your date to a proper string format:

1. Use some external Javascript library 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), something as easy as the code below should do the job:

    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.

Wrap it in a function to re-use it as needed:

function convertDateToString(date) {
        let day = date.getDay();
        let month = date.getMonth() + 1;
        let year = date.getFullYear();
        let yyyy_MM_dd = year + "-" + month + "-" + day; // That's your formatted date.
        return yyyy_MM_dd;
}
2 Likes
  1. is not work cause the getDay() method returns the day of the week [0-6] but not [1-28/29/30/31] as expected.