javascriptjqueryasp.netdate

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery


Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.

Code Snippet:

 function GetDateFormat(controlName) {
        if ($('#' + controlName).val() != "") {      
            var d1 = Date.parse($('#' + controlName).val());
            if (d1 == null) {
                alert('Date Invalid.');
                $('#' + controlName).val("");
            }
                var array = d1.toString('dd-MMM-yyyy');
                $('#' + controlName).val(array);
        }
    }

This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.


Solution

  • You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations

    Then you can do things like:

    var day = moment("12-25-1995", "MM-DD-YYYY");
    

    or

    var day = moment("25/12/1995", "DD/MM/YYYY");
    

    then operate on the date

    day.add('days', 7)
    

    and to get the native javascript date

    day.toDate();