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

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42
puddinman13
  • 1,408
  • 4
  • 18
  • 35

2 Answers2

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.

Community
  • 1
  • 1
Amitd
  • 4,769
  • 8
  • 56
  • 82
  • Thank you very much @Amitd. That solves one problem. Unfortunately the second comma is still in the output from javascript and the hour is not two digits. If you look at the first example in this article: https://msdn.microsoft.com/en-us/library/ie/ff743760%28v=vs.94%29.aspx It shows the time can be shown as 06:00. Is Chrome incompatible with this ability? – puddinman13 Feb 16 '15 at 16:23
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/

puddinman13
  • 1,408
  • 4
  • 18
  • 35