Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intl.DateTimeFormat options hash: Getting leading zeros with '2-digit'

Intl.DateTimeFormat('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
}).format(807959700000)

I expected the above call to return something like Wednesday, August 09, 1995, 04:15:00 AM but it seems the leading zero for the hour is missing. I get Wednesday, August 09, 1995, 4:15:00 AM

2-digit does not do the trick, though it seems to work for the day of the month. Does 2-digit mean something else than I expect, or am I doing something wrong?

P.S. I tested this in the Chrome console, nowhere else.

like image 907
pgblu Avatar asked Oct 28 '15 21:10

pgblu


1 Answers

This will work if you set hour12 property to false. i.e.

Intl.DateTimeFormat('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false     // setting 24 hour format 
}).format(807959700000);

It works for both 2am and also 2pm(14hr). But I know the same should work for 12 hour format too, but it is not. I checked in both chrome and firefox browsers.

When I checked the specs, it has defined an algorithm which can be used to implement Intl.DateTimeFormat functionality. I saw there were many special cases handled when hour12 property to set true, and one of the last step is

  1. If dateTimeFormat has an internal property [[hour12]] whose value is true, then
    • If pm is true, then let fv be an implementation and locale dependent String value representing “post meridiem”; else let fv be an implementation and locale dependent String value representing “ante meridiem”.
    • Replace the substring of result that consists of "{ampm}", with fv.

So I think, the Intl.DateTimeFormat initially works with date object, later at step(8), it applies this step to put am/pm information.

During this step, may be 2-digits information specified in Intl.DateTimeFormat is not considered, but it has to be. I think this is a valid bug and it is already raised https://code.google.com/p/chromium/issues/detail?id=527926.


PS: I'm not saying issue is in specs, as described in the ECMAScript Language Specification,

Algorithms are used to precisely specify the required semantics of ECMAScript constructs, but are not intended to imply the use of any specific implementation technique.

like image 125
rajuGT Avatar answered Oct 22 '22 15:10

rajuGT