JavaScript implements string conversion to date type

Reference

JavaScript Date String

Convert date type to string

The function of the following example function is to input a date type variable and convert it into a string output in yyyy-MM-dd format. If you need to include hours, minutes and seconds, please add them yourself. If you need to convert to other formats, you can also modify it as needed.

            function dateToString(date) {
    if (!date) {
        date = new Date();
    }
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}
        

Convert date of string type to date type

The function of this function is to convert a string in yyyy-MM-dd format into a date type. This function and the above functions can be used in pairs.

            function stringToDate(dateString) {
    if (!dateString) {
        return new Date();
    }
    var dateList = dateString.split("-");
    var year = parseInt(dateList[0], 10);
    var month = parseInt(dateList[1], 10) - 1;
    var day = parseInt(dateList[2], 10);
    return new Date(year, month, day);
}
        

Other tips

It is important to note that in JavaScript, the month starts from 0, so 0 means January. The Date object also contains many other methods. For details, please refer to the references at the top of this article.