2

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

4

2 回答 2

2

You have a typo in your code ..

Instead of seconds: '2-digit' it should be second: '2-digit'

Updated your fiddle https://jsfiddle.net/gxze230b/3/

Edit : After looking for a while think its better to use the answers given here
Where can I find documentation on formatting a date in JavaScript?

Seems not all combinations are supported for now.

于 2015-02-16T16:21:02.533 回答
0

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/

于 2015-02-16T19:11:25.460 回答