Search code examples
javascriptdatedatepickerdate-formattime-format

How do i convert "2016-03-10 16:00:00.0" to March 10,2016 in JavaScript?


I'm getting a date string which i need to convert into other date format in the javascript.

  • Input Date String : 2016-03-10 16:00:00.0

  • Expected Output : March 10,2016


Solution

  • All browsers

    The most reliable way to format a date with the source format you're using, is to apply the following steps :

    1. Use .replace(/ /g,'T') to convert your date to ISO 8601
    2. Use that as input for new Date()
    3. Use .getDate(), .getMonth() and .getFullYear() to get respectively the day, month and year
    4. Paste the pieces together according to your target format

    The format function below shows you the optimal way to combine those four steps :

    var date = '2016-03-10 16:00:00.0';
    
    function format(input) {
        var date = new Date(input.replace(/ /g,'T'));
        return [
            "January", "February", "March", "April", "May", "June", "July",
            "August", "September", "October", "November", "December"
        ][date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear();
    }
    
    document.body.innerHTML = format(date); // OUTPUT : "March 10, 2016"

    (See also this Fiddle).

    Modern browsers only

    You can also use the built-in .toLocaleDateString method to do the formatting for you. You just need pass along the proper locale and options to match the right format, which unfortunately is only supported by modern browsers (*) :

    var date = '2016-03-10 16:00:00.0';
    
    function format(input) {
        var dateFormat = { year: 'numeric', month: 'long', day: 'numeric' };
        return new Date(input.replace(/ /g,'T')).toLocaleDateString('en-US', dateFormat);
    }
    
    document.body.innerHTML = format(date); // OUTPUT : "March 10, 2016"

    (See also this Fiddle).


    (*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build