Search code examples
javascriptjqueryecmascript-intl

Formatting Date and Time With ECMAScript Internationalization API


I need to have a javascript date/time formatted like:

February 16, 2015 06:31:00 AM

I was going to use toLocaleTimeString with some options, but the code I tried below doesn't seem to work in Chrome.

function getFormattedDateTime(dateTimeToFormat) {
dateTimeToFormat = new Date(dateTimeToFormat);
var monthOptions = {
    month: 'long', year: 'numeric', day: 'numeric',
    hour: '2-digit', minute: '2-digit', second: '2-digit'
};

return dateTimeToFormat.toLocaleTimeString('en-us', monthOptions);
}

The output from the above code is February 16, 2015, 6:31 AM

It's close, but no cigar. jQuery is an option as well if it has any better date formatting utilities. jQuery only though, no plugins, please.

Here is a JSFiddle to save some time: https://jsfiddle.net/gxze230b/

After a typo correction, the output string is now: February 16, 2015, 6:31:00 AM


Solution

  • Thanks to guidance from @Amitd, I was able to formulate a method that will produce the expected output of February 16, 2015 06:31:00 AM

    function getFormattedDateTime(dateTimeToFormat) {dateTimeToFormat = new Date(dateTimeToFormat);
    
    var zeroPad = function (val) {
        return (val <= 9 ? '0' + val : '' + val);
    };
    
    var month = dateTimeToFormat.toLocaleString('en-us', {month: "long"});
    var day = dateTimeToFormat.getDate();
    var year = dateTimeToFormat.getFullYear();
    
    var hour = ((dateTimeToFormat.getHours() + 11) % 12 + 1);
    var minutes = dateTimeToFormat.getMinutes();
    var seconds = dateTimeToFormat.getSeconds();
    var suffix = (hour <= 12) ? 'AM' : 'PM';
    
    return month + ' ' + zeroPad(day) + ', ' + year + ' ' + zeroPad(hour) + ':' + zeroPad(minutes) + ':' + zeroPad(seconds) + ' ' + suffix;
    }
    

    JSFiddle: https://jsfiddle.net/puddinman13/L0128fL9/