]>
git.wh0rd.org - tt-rss.git/blob - lib/dojo/date/locale.js.uncompressed.js
1 define("dojo/date/locale", [
5 /*===== "../_base/declare", =====*/
6 "../cldr/supplemental",
10 "../i18n!../cldr/nls/gregorian",
12 ], function(lang
, array
, date
, /*===== declare, =====*/ supplemental
, i18n
, regexp
, string
, gregorian
, module
){
19 // This modules defines dojo/date/locale, localization methods for Date.
21 lang
.setObject(module
.id
.replace(/\//g, "."), exports
);
23 // Localization methods for Date. Honor local customs using locale-dependent dojo.cldr data.
25 // Load the bundles containing localization information for
28 //NOTE: Everything in this module assumes Gregorian calendars.
29 // Other calendars will be implemented in separate modules.
31 // Format a pattern without literals
32 function formatPattern(dateObject
, bundle
, options
, pattern
){
33 return pattern
.replace(/([a-z])\1*/ig, function(match
){
37 widthList
= ["abbr", "wide", "narrow"];
40 s
= bundle
[(l
< 4) ? "eraAbbr" : "eraNames"][dateObject
.getFullYear() < 0 ? 0 : 1];
43 s
= dateObject
.getFullYear();
48 if(!options
.fullYear
){
49 s
= String(s
); s
= s
.substr(s
.length
- 2);
59 s
= Math
.ceil((dateObject
.getMonth()+1)/3);
64 // case 3: case 4: // unimplemented
69 var m
= dateObject
.getMonth();
75 c
== 'L' ? "standAlone" : "format",
83 s
= exports
._getWeekOfYear(dateObject
, firstDay
); pad
= true;
86 s
= dateObject
.getDate(); pad
= true;
89 s
= exports
._getDayOfYear(dateObject
); pad
= true;
93 var d
= dateObject
.getDay();
95 s
= (d
- supplemental
.getFirstDayOfWeek(options
.locale
) + 8) % 7
100 d
= dateObject
.getDay();
106 c
== 'c' ? "standAlone" : "format",
109 s
= bundle
[propD
][d
];
113 var timePeriod
= dateObject
.getHours() < 12 ? 'am' : 'pm';
114 s
= options
[timePeriod
] || bundle
['dayPeriods-format-wide-' + timePeriod
];
120 var h
= dateObject
.getHours();
121 // strange choices in the date format make it impossible to write this succinctly
139 s
= dateObject
.getMinutes(); pad
= true;
142 s
= dateObject
.getSeconds(); pad
= true;
145 s
= Math
.round(dateObject
.getMilliseconds() * Math
.pow(10, l
-3)); pad
= true;
147 case 'v': // FIXME: don't know what this is. seems to be same as z?
149 // We only have one timezone to offer; the one from the browser
150 s
= exports
._getZone(dateObject
, true, options
);
153 // fallthrough... use GMT if tz not available
155 var offset
= exports
._getZone(dateObject
, false, options
);
157 (offset
<=0 ? "+" : "-"),
158 string
.pad(Math
.floor(Math
.abs(offset
)/60), 2),
159 string
.pad(Math
.abs(offset
)% 60, 2)
162 tz
.splice(0, 0, "GMT");
163 tz
.splice(3, 0, ":");
167 // case 'Y': case 'u': case 'W': case 'F': case 'g': case 'A':
168 // console.log(match+" modifier unimplemented");
170 throw new Error("dojo.date.locale.format: invalid pattern char: "+pattern
);
172 if(pad
){ s
= string
.pad(s
, l
); }
178 var __FormatOptions = exports.__FormatOptions = declare(null, {
180 // choice of 'time','date' (default: date and time)
181 // formatLength: String
182 // choice of long, short, medium or full (plus any custom additions). Defaults to 'short'
183 // datePattern:String
184 // override pattern with this string
185 // timePattern:String
186 // override pattern with this string
188 // override strings for am in times
190 // override strings for pm in times
192 // override the locale used to determine formatting rules
194 // (format only) use 4 digit years whenever 2 digit years are called for
196 // (parse only) strict parsing, off by default
200 exports
._getZone = function(/*Date*/ dateObject
, /*boolean*/ getName
, /*__FormatOptions?*/ options
){
202 // Returns the zone (or offset) for the given date and options. This
203 // is broken out into a separate function so that it can be overridden
204 // by timezone-aware code.
207 // the date and/or time being formatted.
210 // Whether to return the timezone string (if true), or the offset (if false)
213 // The options being used for formatting
215 return date
.getTimezoneName(dateObject
);
217 return dateObject
.getTimezoneOffset();
222 exports
.format = function(/*Date*/ dateObject
, /*__FormatOptions?*/ options
){
224 // Format a Date object as a String, using locale-specific settings.
227 // Create a string from a Date object using a known localized pattern.
228 // By default, this method formats both date and time from dateObject.
229 // Formatting patterns are chosen appropriate to the locale. Different
230 // formatting lengths may be chosen, with "full" used by default.
231 // Custom patterns may be used or registered with translations using
232 // the dojo/date/locale.addCustomFormats() method.
233 // Formatting patterns are implemented using [the syntax described at
234 // unicode.org](http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns)
237 // the date and/or time to be formatted. If a time only is formatted,
238 // the values in the year, month, and day fields are irrelevant. The
239 // opposite is true when formatting only dates.
241 options
= options
|| {};
243 var locale
= i18n
.normalizeLocale(options
.locale
),
244 formatLength
= options
.formatLength
|| 'short',
245 bundle
= exports
._getGregorianBundle(locale
),
247 sauce
= lang
.hitch(this, formatPattern
, dateObject
, bundle
, options
);
248 if(options
.selector
== "year"){
249 return _processPattern(bundle
["dateFormatItem-yyyy"] || "yyyy", sauce
);
252 if(options
.selector
!= "date"){
253 pattern
= options
.timePattern
|| bundle
["timeFormat-"+formatLength
];
254 if(pattern
){str
.push(_processPattern(pattern
, sauce
));}
256 if(options
.selector
!= "time"){
257 pattern
= options
.datePattern
|| bundle
["dateFormat-"+formatLength
];
258 if(pattern
){str
.push(_processPattern(pattern
, sauce
));}
261 return str
.length
== 1 ? str
[0] : bundle
["dateTimeFormat-"+formatLength
].replace(/\'/g,'').replace(/\{(\d+)\}/g,
262 function(match
, key
){ return str
[key
]; }); // String
265 exports
.regexp = function(/*__FormatOptions?*/ options
){
267 // Builds the regular needed to parse a localized date
269 return exports
._parseInfo(options
).regexp
; // String
272 exports
._parseInfo = function(/*__FormatOptions?*/ options
){
273 options
= options
|| {};
274 var locale
= i18n
.normalizeLocale(options
.locale
),
275 bundle
= exports
._getGregorianBundle(locale
),
276 formatLength
= options
.formatLength
|| 'short',
277 datePattern
= options
.datePattern
|| bundle
["dateFormat-" + formatLength
],
278 timePattern
= options
.timePattern
|| bundle
["timeFormat-" + formatLength
],
280 if(options
.selector
== 'date'){
281 pattern
= datePattern
;
282 }else if(options
.selector
== 'time'){
283 pattern
= timePattern
;
285 pattern
= bundle
["dateTimeFormat-"+formatLength
].replace(/\{(\d+)\}/g,
286 function(match
, key
){ return [timePattern
, datePattern
][key
]; });
290 re
= _processPattern(pattern
, lang
.hitch(this, _buildDateTimeRE
, tokens
, bundle
, options
));
291 return {regexp
: re
, tokens
: tokens
, bundle
: bundle
};
294 exports
.parse = function(/*String*/ value
, /*__FormatOptions?*/ options
){
296 // Convert a properly formatted string to a primitive Date object,
297 // using locale-specific settings.
300 // Create a Date object from a string using a known localized pattern.
301 // By default, this method parses looking for both date and time in the string.
302 // Formatting patterns are chosen appropriate to the locale. Different
303 // formatting lengths may be chosen, with "full" used by default.
304 // Custom patterns may be used or registered with translations using
305 // the dojo/date/locale.addCustomFormats() method.
307 // Formatting patterns are implemented using [the syntax described at
308 // unicode.org](http://www.unicode.org/reports/tr35/tr35-4.html#Date_Format_Patterns)
309 // When two digit years are used, a century is chosen according to a sliding
310 // window of 80 years before and 20 years after present year, for both `yy` and `yyyy` patterns.
311 // year < 100CE requires strict mode.
314 // A string representation of a date
316 // remove non-printing bidi control chars from input and pattern
317 var controlChars
= /[\u200E\u200F\u202A\u202E]/g,
318 info
= exports
._parseInfo(options
),
319 tokens
= info
.tokens
, bundle
= info
.bundle
,
320 re
= new RegExp("^" + info
.regexp
.replace(controlChars
, "") + "$",
321 info
.strict
? "" : "i"),
322 match
= re
.exec(value
&& value
.replace(controlChars
, ""));
324 if(!match
){ return null; } // null
326 var widthList
= ['abbr', 'wide', 'narrow'],
327 result
= [1970,0,1,0,0,0,0], // will get converted to a Date at the end
329 valid
= array
.every(match
, function(v
, i
){
331 var token
= tokens
[i
-1],
336 if(l
!= 2 && options
.strict
){
337 //interpret year literally, so '5' would be 5 A.D.
342 //choose century to apply, according to a sliding window
343 //of 80 years before and 20 years after present year
344 var year
= '' + new Date().getFullYear(),
345 century
= year
.substring(0, 2) * 100,
346 cutoff
= Math
.min(Number(year
.substring(2, 4)) + 20, 99);
347 result
[0] = (v
< cutoff
) ? century
+ v
: century
- 100 + v
;
349 //we expected 2 digits and got more...
353 //interpret literally, so '150' would be 150 A.D.
354 //also tolerate '1950', if 'yyyy' input passed to 'yy' format
362 var months
= bundle
['months-' +
363 (c
== 'L' ? 'standAlone' : 'format') +
364 '-' + widthList
[l
-3]].concat();
366 //Tolerate abbreviating period in month part
367 //Case-insensitive comparison
368 v
= v
.replace(".","").toLowerCase();
369 months
= array
.map(months
, function(s
){ return s
.replace(".","").toLowerCase(); } );
371 v
= array
.indexOf(months
, v
);
373 // console.log("dojo/date/locale.parse: Could not parse month name: '" + v + "'.");
384 var days
= bundle
['days-' +
385 (c
== 'c' ? 'standAlone' : 'format') +
386 '-' + widthList
[l
-3]].concat();
388 //Case-insensitive comparison
390 days
= array
.map(days
, function(d
){return d
.toLowerCase();});
392 v
= array
.indexOf(days
, v
);
394 // console.log("dojo/date/locale.parse: Could not parse weekday name: '" + v + "'.");
398 //TODO: not sure what to actually do with this input,
399 //in terms of setting something on the Date obj...?
400 //without more context, can't affect the actual date
401 //TODO: just validate?
410 var am
= options
.am
|| bundle
['dayPeriods-format-wide-am'],
411 pm
= options
.pm
|| bundle
['dayPeriods-format-wide-pm'];
414 v
= v
.replace(period
,'').toLowerCase();
415 am
= am
.replace(period
,'').toLowerCase();
416 pm
= pm
.replace(period
,'').toLowerCase();
418 if(options
.strict
&& v
!= am
&& v
!= pm
){
419 // console.log("dojo/date/locale.parse: Could not parse am/pm part.");
423 // we might not have seen the hours field yet, so store the state and apply hour change later
424 amPm
= (v
== pm
) ? 'p' : (v
== am
) ? 'a' : '';
426 case 'K': //hour (1-24)
427 if(v
== 24){ v
= 0; }
429 case 'h': //hour (1-12)
430 case 'H': //hour (0-23)
431 case 'k': //hour (0-11)
432 //TODO: strict bounds checking, padding
434 // console.log("dojo/date/locale.parse: Illegal hours value");
438 //in the 12-hour case, adjusting for am/pm requires the 'a' part
439 //which could come before or after the hour, so we will adjust later
448 case 'S': //milliseconds
452 //TODO var firstDay = 0;
455 // console.log("dojo/date/locale.parse: unsupported pattern char=" + token.charAt(0));
460 var hours
= +result
[3];
461 if(amPm
=== 'p' && hours
< 12){
462 result
[3] = hours
+ 12; //e.g., 3pm -> 15
463 }else if(amPm
=== 'a' && hours
== 12){
464 result
[3] = 0; //12am -> 0
467 //TODO: implement a getWeekday() method in order to test
468 //validity of input strings containing 'EEE' or 'EEEE'...
470 var dateObject
= new Date(result
[0], result
[1], result
[2], result
[3], result
[4], result
[5], result
[6]); // Date
472 dateObject
.setFullYear(result
[0]);
475 // Check for overflow. The Date() constructor normalizes things like April 32nd...
476 //TODO: why isn't this done for times as well?
477 var allTokens
= tokens
.join(""),
478 dateToken
= allTokens
.indexOf('d') != -1,
479 monthToken
= allTokens
.indexOf('M') != -1;
482 (monthToken
&& dateObject
.getMonth() > result
[1]) ||
483 (dateToken
&& dateObject
.getDate() > result
[2])){
487 // Check for underflow, due to DST shifts. See #9366
488 // This assumes a 1 hour dst shift correction at midnight
489 // We could compare the timezone offset after the shift and add the difference instead.
490 if((monthToken
&& dateObject
.getMonth() < result
[1]) ||
491 (dateToken
&& dateObject
.getDate() < result
[2])){
492 dateObject
= date
.add(dateObject
, "hour", 1);
495 return dateObject
; // Date
498 function _processPattern(pattern
, applyPattern
, applyLiteral
, applyAll
){
499 //summary: Process a pattern with literals in it
501 // Break up on single quotes, treat every other one as a literal, except '' which becomes '
502 var identity = function(x
){return x
;};
503 applyPattern
= applyPattern
|| identity
;
504 applyLiteral
= applyLiteral
|| identity
;
505 applyAll
= applyAll
|| identity
;
507 //split on single quotes (which escape literals in date format strings)
508 //but preserve escaped single quotes (e.g., o''clock)
509 var chunks
= pattern
.match(/(''|[^'])+/g),
510 literal
= pattern
.charAt(0) == "'";
512 array
.forEach(chunks
, function(chunk
, i
){
516 chunks
[i
]=(literal
? applyLiteral
: applyPattern
)(chunk
.replace(/''/g, "'"));
520 return applyAll(chunks
.join(''));
523 function _buildDateTimeRE(tokens
, bundle
, options
, pattern
){
524 pattern
= regexp
.escapeString(pattern
);
525 if(!options
.strict
){ pattern
= pattern
.replace(" a", " ?a"); } // kludge to tolerate no space before am/pm
526 return pattern
.replace(/([a-z])\1*/ig, function(match
){
527 // Build a simple regexp. Avoid captures, which would ruin the tokens list
533 if(l
> 1){ p2
= '0' + '{'+(l
-1)+'}'; }
534 if(l
> 2){ p3
= '0' + '{'+(l
-2)+'}'; }
536 p2
= '0?'; p3
= '0{0,2}';
544 s
= (l
>2) ? '\\S+?' : '1[0-2]|'+p2
+'[1-9]';
547 s
= '[12][0-9][0-9]|3[0-5][0-9]|36[0-6]|'+p2
+'[1-9][0-9]|'+p3
+'[1-9]';
550 s
= '3[01]|[12]\\d|'+p2
+'[1-9]';
553 s
= '[1-4][0-9]|5[0-3]|'+p2
+'[1-9]';
560 case 'h': //hour (1-12)
561 s
= '1[0-2]|'+p2
+'[1-9]';
563 case 'k': //hour (0-11)
564 s
= '1[01]|'+p2
+'\\d';
566 case 'H': //hour (0-23)
567 s
= '1\\d|2[0-3]|'+p2
+'\\d';
569 case 'K': //hour (1-24)
570 s
= '1\\d|2[0-4]|'+p2
+'[1-9]';
580 var am
= options
.am
|| bundle
['dayPeriods-format-wide-am'],
581 pm
= options
.pm
|| bundle
['dayPeriods-format-wide-pm'];
584 if(am
!= am
.toLowerCase()){ s
+= '|' + am
.toLowerCase(); }
585 if(pm
!= pm
.toLowerCase()){ s
+= '|' + pm
.toLowerCase(); }
586 if(s
.indexOf('.') != -1){ s
+= '|' + s
.replace(/\./g, ""); }
588 s
= s
.replace(/\./g, "\\.");
595 // console.log("parse of date format, pattern=" + pattern);
598 if(tokens
){ tokens
.push(match
); }
600 return "(" + s
+ ")"; // add capture
601 }).replace(/[\xa0 ]/g, "[\\s\\xa0]"); // normalize whitespace. Need explicit handling of \xa0 for IE.
604 var _customFormats
= [];
605 exports
.addCustomFormats = function(/*String*/ packageName
, /*String*/ bundleName
){
607 // Add a reference to a bundle containing localized custom formats to be
608 // used by date/time formatting and parsing routines.
611 // The user may add custom localized formats where the bundle has properties following the
612 // same naming convention used by dojo.cldr: `dateFormat-xxxx` / `timeFormat-xxxx`
613 // The pattern string should match the format used by the CLDR.
614 // See dojo/date/locale.format() for details.
615 // The resources must be loaded by dojo.requireLocalization() prior to use
617 _customFormats
.push({pkg
:packageName
,name
:bundleName
});
620 exports
._getGregorianBundle = function(/*String*/ locale
){
622 array
.forEach(_customFormats
, function(desc
){
623 var bundle
= i18n
.getLocalization(desc
.pkg
, desc
.name
, locale
);
624 gregorian
= lang
.mixin(gregorian
, bundle
);
626 return gregorian
; /*Object*/
629 exports
.addCustomFormats(module
.id
.replace(/\/date\/locale$/, ".cldr"),"gregorian");
631 exports
.getNames = function(/*String*/ item
, /*String*/ type
, /*String?*/ context
, /*String?*/ locale
){
633 // Used to get localized strings from dojo.cldr for day or month names.
636 // 'months' || 'days'
638 // 'wide' || 'abbr' || 'narrow' (e.g. "Monday", "Mon", or "M" respectively, in English)
640 // 'standAlone' || 'format' (default)
642 // override locale used to find the names
645 lookup
= exports
._getGregorianBundle(locale
),
646 props
= [item
, context
, type
];
647 if(context
== 'standAlone'){
648 var key
= props
.join('-');
650 // Fall back to 'format' flavor of name
651 if(label
[0] == 1){ label
= undefined; } // kludge, in the absence of real aliasing support in dojo.cldr
655 // return by copy so changes won't be made accidentally to the in-memory model
656 return (label
|| lookup
[props
.join('-')]).concat(); /*Array*/
659 exports
.isWeekend = function(/*Date?*/ dateObject
, /*String?*/ locale
){
661 // Determines if the date falls on a weekend, according to local custom.
663 var weekend
= supplemental
.getWeekend(locale
),
664 day
= (dateObject
|| new Date()).getDay();
665 if(weekend
.end
< weekend
.start
){
667 if(day
< weekend
.start
){ day
+= 7; }
669 return day
>= weekend
.start
&& day
<= weekend
.end
; // Boolean
672 // These are used only by format and strftime. Do they need to be public? Which module should they go in?
674 exports
._getDayOfYear = function(/*Date*/ dateObject
){
676 // gets the day of the year as represented by dateObject
677 return date
.difference(new Date(dateObject
.getFullYear(), 0, 1, dateObject
.getHours()), dateObject
) + 1; // Number
680 exports
._getWeekOfYear = function(/*Date*/ dateObject
, /*Number*/ firstDayOfWeek
){
681 if(arguments
.length
== 1){ firstDayOfWeek
= 0; } // Sunday
683 var firstDayOfYear
= new Date(dateObject
.getFullYear(), 0, 1).getDay(),
684 adj
= (firstDayOfYear
- firstDayOfWeek
+ 7) % 7,
685 week
= Math
.floor((exports
._getDayOfYear(dateObject
) + adj
- 1) / 7);
687 // if year starts on the specified day, start counting weeks at 1
688 if(firstDayOfYear
== firstDayOfWeek
){ week
++; }
690 return week
; // Number