Debian Codegraph @

closure-library/closure/goog/date/date.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Functions and objects for date representation and manipulation.
17 *
18 * @author [email protected] (Emil A Eklund)
19 */
20
21 goog.provide('goog.date');
22 goog.provide('goog.date.Date');
23 goog.provide('goog.date.DateTime');
24 goog.provide('goog.date.Interval');
25 goog.provide('goog.date.month');
26 goog.provide('goog.date.weekDay');
27
28 goog.require('goog.asserts');
29 /** @suppress {extraRequire} */
30 goog.require('goog.date.DateLike');
31 goog.require('goog.i18n.DateTimeSymbols');
32 goog.require('goog.string');
33
34
35 /**
36 * Constants for weekdays.
37 * @enum {number}
38 */
39 goog.date.weekDay = {
40 MON: 0,
41 TUE: 1,
42 WED: 2,
43 THU: 3,
44 FRI: 4,
45 SAT: 5,
46 SUN: 6
47 };
48
49
50 /**
51 * Constants for months.
52 * @enum {number}
53 */
54 goog.date.month = {
55 JAN: 0,
56 FEB: 1,
57 MAR: 2,
58 APR: 3,
59 MAY: 4,
60 JUN: 5,
61 JUL: 6,
62 AUG: 7,
63 SEP: 8,
64 OCT: 9,
65 NOV: 10,
66 DEC: 11
67 };
68
69
70 /**
71 * Formats a month/year string.
72 * Example: "January 2008"
73 *
74 * @param {string} monthName The month name to use in the result.
75 * @param {number} yearNum The numeric year to use in the result.
76 * @return {string} A formatted month/year string.
77 */
78 goog.date.formatMonthAndYear = function(monthName, yearNum) {
79 /** @desc Month/year format given the month name and the numeric year. */
80 var MSG_MONTH_AND_YEAR = goog.getMsg(
81 '{$monthName} {$yearNum}',
82 {'monthName': monthName, 'yearNum': String(yearNum)});
83 return MSG_MONTH_AND_YEAR;
84 };
85
86
87 /**
88 * Regular expression for splitting date parts from ISO 8601 styled string.
89 * Examples: '20060210' or '2005-02-22' or '20050222' or '2005-08'
90 * or '2005-W22' or '2005W22' or '2005-W22-4', etc.
91 * For explanation and more examples, see:
92 * {@link http://en.wikipedia.org/wiki/ISO_8601}
93 *
94 * @type {RegExp}
95 * @private
96 */
97 goog.date.splitDateStringRegex_ = new RegExp(
98 '^(\\d{4})(?:(?:-?(\\d{2})(?:-?(\\d{2}))?)|' +
99 '(?:-?(\\d{3}))|(?:-?W(\\d{2})(?:-?([1-7]))?))?$');
100
101
102 /**
103 * Regular expression for splitting time parts from ISO 8601 styled string.
104 * Examples: '18:46:39.994' or '184639.994'
105 *
106 * @type {RegExp}
107 * @private
108 */
109 goog.date.splitTimeStringRegex_ =
110 /^(\d{2})(?::?(\d{2})(?::?(\d{2})(\.\d+)?)?)?$/;
111
112
113 /**
114 * Regular expression for splitting timezone parts from ISO 8601 styled string.
115 * Example: The part after the '+' in '18:46:39+07:00'. Or '09:30Z' (UTC).
116 *
117 * @type {RegExp}
118 * @private
119 */
120 goog.date.splitTimezoneStringRegex_ = /Z|(?:([-+])(\d{2})(?::?(\d{2}))?)$/;
121
122
123 /**
124 * Regular expression for splitting duration parts from ISO 8601 styled string.
125 * Example: '-P1Y2M3DT4H5M6.7S'
126 *
127 * @type {RegExp}
128 * @private
129 */
130 goog.date.splitDurationRegex_ = new RegExp(
131 '^(-)?P(?:(\\d+)Y)?(?:(\\d+)M)?(?:(\\d+)D)?' +
132 '(T(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$');
133
134
135 /**
136 * Number of milliseconds in a day.
137 * @type {number}
138 */
139 goog.date.MS_PER_DAY = 24 * 60 * 60 * 1000;
140
141
142 /**
143 * Returns whether the given year is a leap year.
144 *
145 * @param {number} year Year part of date.
146 * @return {boolean} Whether the given year is a leap year.
147 */
148 goog.date.isLeapYear = function(year) {
149 // Leap year logic; the 4-100-400 rule
150 return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
151 };
152
153
154 /**
155 * Returns whether the given year is a long ISO year.
156 * See {@link http://www.phys.uu.nl/~vgent/calendar/isocalendar_text3.htm}.
157 *
158 * @param {number} year Full year part of date.
159 * @return {boolean} Whether the given year is a long ISO year.
160 */
161 goog.date.isLongIsoYear = function(year) {
162 var n = 5 * year + 12 - 4 * (Math.floor(year / 100) - Math.floor(year / 400));
163 n += Math.floor((year - 100) / 400) - Math.floor((year - 102) / 400);
164 n += Math.floor((year - 200) / 400) - Math.floor((year - 199) / 400);
165
166 return n % 28 < 5;
167 };
168
169
170 /**
171 * Returns the number of days for a given month.
172 *
173 * @param {number} year Year part of date.
174 * @param {number} month Month part of date.
175 * @return {number} The number of days for the given month.
176 */
177 goog.date.getNumberOfDaysInMonth = function(year, month) {
178 switch (month) {
179 case goog.date.month.FEB:
180 return goog.date.isLeapYear(year) ? 29 : 28;
181 case goog.date.month.JUN:
182 case goog.date.month.SEP:
183 case goog.date.month.NOV:
184 case goog.date.month.APR:
185 return 30;
186 }
187 return 31;
188 };
189
190
191 /**
192 * Returns true if the 2 dates are in the same day.
193 * @param {goog.date.DateLike} date The time to check.
194 * @param {goog.date.DateLike=} opt_now The current time.
195 * @return {boolean} Whether the dates are on the same day.
196 */
197 goog.date.isSameDay = function(date, opt_now) {
198 var now = opt_now || new Date(goog.now());
199 return date.getDate() == now.getDate() && goog.date.isSameMonth(date, now);
200 };
201
202
203 /**
204 * Returns true if the 2 dates are in the same month.
205 * @param {goog.date.DateLike} date The time to check.
206 * @param {goog.date.DateLike=} opt_now The current time.
207 * @return {boolean} Whether the dates are in the same calendar month.
208 */
209 goog.date.isSameMonth = function(date, opt_now) {
210 var now = opt_now || new Date(goog.now());
211 return date.getMonth() == now.getMonth() && goog.date.isSameYear(date, now);
212 };
213
214
215 /**
216 * Returns true if the 2 dates are in the same year.
217 * @param {goog.date.DateLike} date The time to check.
218 * @param {goog.date.DateLike=} opt_now The current time.
219 * @return {boolean} Whether the dates are in the same calendar year.
220 */
221 goog.date.isSameYear = function(date, opt_now) {
222 var now = opt_now || new Date(goog.now());
223 return date.getFullYear() == now.getFullYear();
224 };
225
226
227 /**
228 * Static function for week number calculation. ISO 8601 implementation.
229 *
230 * @param {number} year Year part of date.
231 * @param {number} month Month part of date (0-11).
232 * @param {number} date Day part of date (1-31).
233 * @param {number=} opt_weekDay Cut off weekday, defaults to Thursday.
234 * @param {number=} opt_firstDayOfWeek First day of the week, defaults to
235 * Monday.
236 * Monday=0, Sunday=6.
237 * @return {number} The week number (1-53).
238 */
239 goog.date.getWeekNumber = function(
240 year, month, date, opt_weekDay, opt_firstDayOfWeek) {
241 var d = new Date(year, month, date);
242
243 // Default to Thursday for cut off as per ISO 8601.
244 var cutoff = goog.isDef(opt_weekDay) ? opt_weekDay : goog.date.weekDay.THU;
245
246 // Default to Monday for first day of the week as per ISO 8601.
247 var firstday = opt_firstDayOfWeek || goog.date.weekDay.MON;
248
249 // The d.getDay() has to be converted first to ISO weekday (Monday=0).
250 var isoday = (d.getDay() + 6) % 7;
251
252 // Position of given day in the picker grid w.r.t. first day of week
253 var daypos = (isoday - firstday + 7) % 7;
254
255 // Position of cut off day in the picker grid w.r.t. first day of week
256 var cutoffpos = (cutoff - firstday + 7) % 7;
257
258 // Unix timestamp of the midnight of the cutoff day in the week of 'd'.
259 // There might be +-1 hour shift in the result due to the daylight saving,
260 // but it doesn't affect the year.
261 var cutoffSameWeek =
262 d.valueOf() + (cutoffpos - daypos) * goog.date.MS_PER_DAY;
263
264 // Unix timestamp of January 1 in the year of 'cutoffSameWeek'.
265 var jan1 = new Date(new Date(cutoffSameWeek).getFullYear(), 0, 1).valueOf();
266
267 // Number of week. The round() eliminates the effect of daylight saving.
268 return Math.floor(
269 Math.round((cutoffSameWeek - jan1) / goog.date.MS_PER_DAY) / 7) +
270 1;
271 };
272
273
274 /**
275 * @param {T} date1 A datelike object.
276 * @param {S} date2 Another datelike object.
277 * @return {T|S} The earlier of them in time.
278 * @template T,S
279 */
280 goog.date.min = function(date1, date2) {
281 return date1 < date2 ? date1 : date2;
282 };
283
284
285 /**
286 * @param {T} date1 A datelike object.
287 * @param {S} date2 Another datelike object.
288 * @return {T|S} The later of them in time.
289 * @template T,S
290 */
291 goog.date.max = function(date1, date2) {
292 return date1 > date2 ? date1 : date2;
293 };
294
295
296 /**
297 * Creates a DateTime from a datetime string expressed in ISO 8601 format.
298 *
299 * @param {string} formatted A date or datetime expressed in ISO 8601 format.
300 * @return {goog.date.DateTime} Parsed date or null if parse fails.
301 * @deprecated Use goog.date.Date.fromIsoString() or
302 * goog.date.DateTime.fromIsoString()
303 */
304 goog.date.fromIsoString = function(formatted) {
305 return goog.date.DateTime.fromIsoString(formatted);
306 };
307
308
309 /**
310 * Parses a datetime string expressed in ISO 8601 format. Overwrites the date
311 * and optionally the time part of the given object with the parsed values.
312 *
313 * @param {!goog.date.DateTime} dateTime Object whose fields will be set.
314 * @param {string} formatted A date or datetime expressed in ISO 8601 format.
315 * @return {boolean} Whether the parsing succeeded.
316 */
317 goog.date.setIso8601DateTime = function(dateTime, formatted) {
318 formatted = goog.string.trim(formatted);
319 var delim = formatted.indexOf('T') == -1 ? ' ' : 'T';
320 var parts = formatted.split(delim);
321 return goog.date.setIso8601DateOnly_(dateTime, parts[0]) &&
322 (parts.length < 2 || goog.date.setIso8601TimeOnly_(dateTime, parts[1]));
323 };
324
325
326 /**
327 * Sets date fields based on an ISO 8601 format string.
328 *
329 * @param {!goog.date.Date} d Object whose fields will be set.
330 * @param {string} formatted A date expressed in ISO 8601 format.
331 * @return {boolean} Whether the parsing succeeded.
332 * @private
333 */
334 goog.date.setIso8601DateOnly_ = function(d, formatted) {
335 // split the formatted ISO date string into its date fields
336 var parts = formatted.match(goog.date.splitDateStringRegex_);
337 if (!parts) {
338 return false;
339 }
340
341 var year = Number(parts[1]);
342 var month = Number(parts[2]);
343 var date = Number(parts[3]);
344 var dayOfYear = Number(parts[4]);
345 var week = Number(parts[5]);
346 // ISO weekdays start with 1, native getDay() values start with 0
347 var dayOfWeek = Number(parts[6]) || 1;
348
349 d.setFullYear(year);
350
351 if (dayOfYear) {
352 d.setDate(1);
353 d.setMonth(0);
354 var offset = dayOfYear - 1; // offset, so 1-indexed, i.e., skip day 1
355 d.add(new goog.date.Interval(goog.date.Interval.DAYS, offset));
356 } else if (week) {
357 goog.date.setDateFromIso8601Week_(d, week, dayOfWeek);
358 } else {
359 if (month) {
360 d.setDate(1);
361 d.setMonth(month - 1);
362 }
363 if (date) {
364 d.setDate(date);
365 }
366 }
367
368 return true;
369 };
370
371
372 /**
373 * Sets date fields based on an ISO 8601 week string.
374 * See {@link http://en.wikipedia.org/wiki/ISO_week_date}, "Relation with the
375 * Gregorian Calendar". The first week of a new ISO year is the week with the
376 * majority of its days in the new Gregorian year. I.e., ISO Week 1's Thursday
377 * is in that year. ISO weeks always start on Monday. So ISO Week 1 can
378 * contain a few days from the previous Gregorian year. And ISO weeks always
379 * end on Sunday, so the last ISO week (Week 52 or 53) can have a few days from
380 * the following Gregorian year.
381 * Example: '1997-W01' lasts from 1996-12-30 to 1997-01-05. January 1, 1997 is
382 * a Wednesday. So W01's Monday is Dec.30, 1996, and Sunday is January 5, 1997.
383 *
384 * @param {!goog.date.Date} d Object whose fields will be set.
385 * @param {number} week ISO week number.
386 * @param {number} dayOfWeek ISO day of week.
387 * @private
388 */
389 goog.date.setDateFromIso8601Week_ = function(d, week, dayOfWeek) {
390 // calculate offset for first week
391 d.setMonth(0);
392 d.setDate(1);
393 var jsDay = d.getDay();
394 // switch Sunday (0) to index 7; ISO days are 1-indexed
395 var jan1WeekDay = jsDay || 7;
396
397 var THURSDAY = 4;
398 if (jan1WeekDay <= THURSDAY) {
399 // was extended back to Monday
400 var startDelta = 1 - jan1WeekDay; // e.g., Thu(4) ==> -3
401 } else {
402 // was extended forward to Monday
403 startDelta = 8 - jan1WeekDay; // e.g., Fri(5) ==> +3
404 }
405
406 // find the absolute number of days to offset from the start of year
407 // to arrive close to the Gregorian equivalent (pending adjustments above)
408 // Note: decrement week multiplier by one because 1st week is
409 // represented by dayOfWeek value
410 var absoluteDays = Number(dayOfWeek) + (7 * (Number(week) - 1));
411
412 // convert from ISO weekday format to Gregorian calendar date
413 // note: subtract 1 because 1-indexed; offset should not include 1st of month
414 var delta = startDelta + absoluteDays - 1;
415 var interval = new goog.date.Interval(goog.date.Interval.DAYS, delta);
416 d.add(interval);
417 };
418
419
420 /**
421 * Sets time fields based on an ISO 8601 format string.
422 * Note: only time fields, not date fields.
423 *
424 * @param {!goog.date.DateTime} d Object whose fields will be set.
425 * @param {string} formatted A time expressed in ISO 8601 format.
426 * @return {boolean} Whether the parsing succeeded.
427 * @private
428 */
429 goog.date.setIso8601TimeOnly_ = function(d, formatted) {
430 // first strip timezone info from the end
431 var parts = formatted.match(goog.date.splitTimezoneStringRegex_);
432
433 var offset = 0; // local time if no timezone info
434 if (parts) {
435 if (parts[0] != 'Z') {
436 offset = Number(parts[2]) * 60 + Number(parts[3]);
437 offset *= parts[1] == '-' ? 1 : -1;
438 }
439 offset -= d.getTimezoneOffset();
440 formatted = formatted.substr(0, formatted.length - parts[0].length);
441 }
442
443 // then work out the time
444 parts = formatted.match(goog.date.splitTimeStringRegex_);
445 if (!parts) {
446 return false;
447 }
448
449 d.setHours(Number(parts[1]));
450 d.setMinutes(Number(parts[2]) || 0);
451 d.setSeconds(Number(parts[3]) || 0);
452 d.setMilliseconds(parts[4] ? Number(parts[4]) * 1000 : 0);
453
454 if (offset != 0) {
455 // adjust the date and time according to the specified timezone
456 d.setTime(d.getTime() + offset * 60000);
457 }
458
459 return true;
460 };
461
462
463
464 /**
465 * Class representing a date/time interval. Used for date calculations.
466 * <pre>
467 * new goog.date.Interval(0, 1) // One month
468 * new goog.date.Interval(0, 0, 3, 1) // Three days and one hour
469 * new goog.date.Interval(goog.date.Interval.DAYS, 1) // One day
470 * </pre>
471 *
472 * @param {number|string=} opt_years Years or string representing date part.
473 * @param {number=} opt_months Months or number of whatever date part specified
474 * by first parameter.
475 * @param {number=} opt_days Days.
476 * @param {number=} opt_hours Hours.
477 * @param {number=} opt_minutes Minutes.
478 * @param {number=} opt_seconds Seconds.
479 * @constructor
480 * @struct
481 * @final
482 */
483 goog.date.Interval = function(
484 opt_years, opt_months, opt_days, opt_hours, opt_minutes, opt_seconds) {
485 if (goog.isString(opt_years)) {
486 var type = opt_years;
487 var interval = /** @type {number} */ (opt_months);
488 /** @type {number} */
489 this.years = type == goog.date.Interval.YEARS ? interval : 0;
490 /** @type {number} */
491 this.months = type == goog.date.Interval.MONTHS ? interval : 0;
492 /** @type {number} */
493 this.days = type == goog.date.Interval.DAYS ? interval : 0;
494 /** @type {number} */
495 this.hours = type == goog.date.Interval.HOURS ? interval : 0;
496 /** @type {number} */
497 this.minutes = type == goog.date.Interval.MINUTES ? interval : 0;
498 /** @type {number} */
499 this.seconds = type == goog.date.Interval.SECONDS ? interval : 0;
500 } else {
501 this.years = /** @type {number} */ (opt_years) || 0;
502 this.months = opt_months || 0;
503 this.days = opt_days || 0;
504 this.hours = opt_hours || 0;
505 this.minutes = opt_minutes || 0;
506 this.seconds = opt_seconds || 0;
507 }
508 };
509
510
511 /**
512 * Parses an XML Schema duration (ISO 8601 extended).
513 * @see http://www.w3.org/TR/xmlschema-2/#duration
514 *
515 * @param {string} duration An XML schema duration in textual format.
516 * Recurring durations and weeks are not supported.
517 * @return {goog.date.Interval} The duration as a goog.date.Interval or null
518 * if the parse fails.
519 */
520 goog.date.Interval.fromIsoString = function(duration) {
521 var parts = duration.match(goog.date.splitDurationRegex_);
522 if (!parts) {
523 return null;
524 }
525
526 var timeEmpty = !(parts[6] || parts[7] || parts[8]);
527 var dateTimeEmpty = timeEmpty && !(parts[2] || parts[3] || parts[4]);
528 if (dateTimeEmpty || timeEmpty && parts[5]) {
529 return null;
530 }
531
532 var negative = parts[1];
533 var years = parseInt(parts[2], 10) || 0;
534 var months = parseInt(parts[3], 10) || 0;
535 var days = parseInt(parts[4], 10) || 0;
536 var hours = parseInt(parts[6], 10) || 0;
537 var minutes = parseInt(parts[7], 10) || 0;
538 var seconds = parseFloat(parts[8]) || 0;
539 return negative ?
540 new goog.date.Interval(
541 -years, -months, -days, -hours, -minutes, -seconds) :
542 new goog.date.Interval(years, months, days, hours, minutes, seconds);
543 };
544
545
546 /**
547 * Serializes goog.date.Interval into XML Schema duration (ISO 8601 extended).
548 * @see http://www.w3.org/TR/xmlschema-2/#duration
549 *
550 * @param {boolean=} opt_verbose Include zero fields in the duration string.
551 * @return {?string} An XML schema duration in ISO 8601 extended format,
552 * or null if the interval contains both positive and negative fields.
553 */
554 goog.date.Interval.prototype.toIsoString = function(opt_verbose) {
555 var minField = Math.min(
556 this.years, this.months, this.days, this.hours, this.minutes,
557 this.seconds);
558 var maxField = Math.max(
559 this.years, this.months, this.days, this.hours, this.minutes,
560 this.seconds);
561 if (minField < 0 && maxField > 0) {
562 return null;
563 }
564
565 // Return 0 seconds if all fields are zero.
566 if (!opt_verbose && minField == 0 && maxField == 0) {
567 return 'PT0S';
568 }
569
570 var res = [];
571
572 // Add sign and 'P' prefix.
573 if (minField < 0) {
574 res.push('-');
575 }
576 res.push('P');
577
578 // Add date.
579 if (this.years || opt_verbose) {
580 res.push(Math.abs(this.years) + 'Y');
581 }
582 if (this.months || opt_verbose) {
583 res.push(Math.abs(this.months) + 'M');
584 }
585 if (this.days || opt_verbose) {
586 res.push(Math.abs(this.days) + 'D');
587 }
588
589 // Add time.
590 if (this.hours || this.minutes || this.seconds || opt_verbose) {
591 res.push('T');
592 if (this.hours || opt_verbose) {
593 res.push(Math.abs(this.hours) + 'H');
594 }
595 if (this.minutes || opt_verbose) {
596 res.push(Math.abs(this.minutes) + 'M');
597 }
598 if (this.seconds || opt_verbose) {
599 res.push(Math.abs(this.seconds) + 'S');
600 }
601 }
602
603 return res.join('');
604 };
605
606
607 /**
608 * Tests whether the given interval is equal to this interval.
609 * Note, this is a simple field-by-field comparison, it doesn't
610 * account for comparisons like "12 months == 1 year".
611 *
612 * @param {goog.date.Interval} other The interval to test.
613 * @return {boolean} Whether the intervals are equal.
614 */
615 goog.date.Interval.prototype.equals = function(other) {
616 return other.years == this.years && other.months == this.months &&
617 other.days == this.days && other.hours == this.hours &&
618 other.minutes == this.minutes && other.seconds == this.seconds;
619 };
620
621
622 /**
623 * @return {!goog.date.Interval} A clone of the interval object.
624 */
625 goog.date.Interval.prototype.clone = function() {
626 return new goog.date.Interval(
627 this.years, this.months, this.days, this.hours, this.minutes,
628 this.seconds);
629 };
630
631
632 /**
633 * Years constant for the date parts.
634 * @type {string}
635 */
636 goog.date.Interval.YEARS = 'y';
637
638
639 /**
640 * Months constant for the date parts.
641 * @type {string}
642 */
643 goog.date.Interval.MONTHS = 'm';
644
645
646 /**
647 * Days constant for the date parts.
648 * @type {string}
649 */
650 goog.date.Interval.DAYS = 'd';
651
652
653 /**
654 * Hours constant for the date parts.
655 * @type {string}
656 */
657 goog.date.Interval.HOURS = 'h';
658
659
660 /**
661 * Minutes constant for the date parts.
662 * @type {string}
663 */
664 goog.date.Interval.MINUTES = 'n';
665
666
667 /**
668 * Seconds constant for the date parts.
669 * @type {string}
670 */
671 goog.date.Interval.SECONDS = 's';
672
673
674 /**
675 * @return {boolean} Whether all fields of the interval are zero.
676 */
677 goog.date.Interval.prototype.isZero = function() {
678 return this.years == 0 && this.months == 0 && this.days == 0 &&
679 this.hours == 0 && this.minutes == 0 && this.seconds == 0;
680 };
681
682
683 /**
684 * @return {!goog.date.Interval} Negative of this interval.
685 */
686 goog.date.Interval.prototype.getInverse = function() {
687 return this.times(-1);
688 };
689
690
691 /**
692 * Calculates n * (this interval) by memberwise multiplication.
693 * @param {number} n An integer.
694 * @return {!goog.date.Interval} n * this.
695 */
696 goog.date.Interval.prototype.times = function(n) {
697 return new goog.date.Interval(
698 this.years * n, this.months * n, this.days * n, this.hours * n,
699 this.minutes * n, this.seconds * n);
700 };
701
702
703 /**
704 * Gets the total number of seconds in the time interval. Assumes that months
705 * and years are empty.
706 * @return {number} Total number of seconds in the interval.
707 */
708 goog.date.Interval.prototype.getTotalSeconds = function() {
709 goog.asserts.assert(this.years == 0 && this.months == 0);
710 return ((this.days * 24 + this.hours) * 60 + this.minutes) * 60 +
711 this.seconds;
712 };
713
714
715 /**
716 * Adds the Interval in the argument to this Interval field by field.
717 *
718 * @param {goog.date.Interval} interval The Interval to add.
719 */
720 goog.date.Interval.prototype.add = function(interval) {
721 this.years += interval.years;
722 this.months += interval.months;
723 this.days += interval.days;
724 this.hours += interval.hours;
725 this.minutes += interval.minutes;
726 this.seconds += interval.seconds;
727 };
728
729
730
731 /**
732 * Class representing a date. Defaults to current date if none is specified.
733 *
734 * Implements most methods of the native js Date object (except the time related
735 * ones, {@see goog.date.DateTime}) and can be used interchangeably with it just
736 * as if goog.date.Date was a synonym of Date. To make this more transparent,
737 * Closure APIs should accept goog.date.DateLike instead of the real Date
738 * object.
739 *
740 * @param {number|goog.date.DateLike=} opt_year Four digit year or a date-like
741 * object. If not set, the created object will contain the date
742 * determined by goog.now().
743 * @param {number=} opt_month Month, 0 = Jan, 11 = Dec.
744 * @param {number=} opt_date Date of month, 1 - 31.
745 * @constructor
746 * @struct
747 * @see goog.date.DateTime
748 */
749 goog.date.Date = function(opt_year, opt_month, opt_date) {
750 /** @protected {!Date} The wrapped date or datetime. */
751 this.date;
752 // goog.date.DateTime assumes that only this.date is added in this ctor.
753 if (goog.isNumber(opt_year)) {
754 this.date = this.buildDate_(opt_year, opt_month || 0, opt_date || 1);
755 this.maybeFixDst_(opt_date || 1);
756 } else if (goog.isObject(opt_year)) {
757 this.date = this.buildDate_(
758 opt_year.getFullYear(), opt_year.getMonth(), opt_year.getDate());
759 this.maybeFixDst_(opt_year.getDate());
760 } else {
761 this.date = new Date(goog.now());
762 var expectedDate = this.date.getDate();
763 this.date.setHours(0);
764 this.date.setMinutes(0);
765 this.date.setSeconds(0);
766 this.date.setMilliseconds(0);
767 // In some time zones there is no "0" hour on certain days during DST.
768 // Adjust here, if necessary. See:
769 // https://github.com/google/closure-library/issues/34.
770 this.maybeFixDst_(expectedDate);
771 }
772 };
773
774
775 /**
776 * new Date(y, m, d) treats years in the interval [0, 100) as two digit years,
777 * adding 1900 to them. This method ensures that calling the date constructor
778 * as a copy constructor returns a value that is equal to the passed in
779 * date value by explicitly setting the full year.
780 * @private
781 * @param {number} fullYear The full year (including century).
782 * @param {number} month The month, from 0-11.
783 * @param {number} date The day of the month.
784 * @return {!Date} The constructed Date object.
785 */
786 goog.date.Date.prototype.buildDate_ = function(fullYear, month, date) {
787 var d = new Date(fullYear, month, date);
788 if (fullYear >= 0 && fullYear < 100) {
789 // Can't just setFullYear as new Date() can flip over for e.g. month = 13.
790 d.setFullYear(d.getFullYear() - 1900);
791 }
792 return d;
793 };
794
795
796 /**
797 * First day of week. 0 = Mon, 6 = Sun.
798 * @type {number}
799 * @private
800 */
801 goog.date.Date.prototype.firstDayOfWeek_ =
802 goog.i18n.DateTimeSymbols.FIRSTDAYOFWEEK;
803
804
805 /**
806 * The cut off weekday used for week number calculations. 0 = Mon, 6 = Sun.
807 * @type {number}
808 * @private
809 */
810 goog.date.Date.prototype.firstWeekCutOffDay_ =
811 goog.i18n.DateTimeSymbols.FIRSTWEEKCUTOFFDAY;
812
813
814 /**
815 * @return {!goog.date.Date} A clone of the date object.
816 */
817 goog.date.Date.prototype.clone = function() {
818 var date = new goog.date.Date(this.date);
819 date.firstDayOfWeek_ = this.firstDayOfWeek_;
820 date.firstWeekCutOffDay_ = this.firstWeekCutOffDay_;
821
822 return date;
823 };
824
825
826 /**
827 * @return {number} The four digit year of date.
828 */
829 goog.date.Date.prototype.getFullYear = function() {
830 return this.date.getFullYear();
831 };
832
833
834 /**
835 * Alias for getFullYear.
836 *
837 * @return {number} The four digit year of date.
838 * @see #getFullYear
839 */
840 goog.date.Date.prototype.getYear = function() {
841 return this.getFullYear();
842 };
843
844
845 /**
846 * @return {goog.date.month} The month of date, 0 = Jan, 11 = Dec.
847 */
848 goog.date.Date.prototype.getMonth = function() {
849 return /** @type {goog.date.month} */ (this.date.getMonth());
850 };
851
852
853 /**
854 * @return {number} The date of month.
855 */
856 goog.date.Date.prototype.getDate = function() {
857 return this.date.getDate();
858 };
859
860
861 /**
862 * Returns the number of milliseconds since 1 January 1970 00:00:00.
863 *
864 * @return {number} The number of milliseconds since 1 January 1970 00:00:00.
865 */
866 goog.date.Date.prototype.getTime = function() {
867 return this.date.getTime();
868 };
869
870
871 /**
872 * @return {number} The day of week, US style. 0 = Sun, 6 = Sat.
873 */
874 goog.date.Date.prototype.getDay = function() {
875 return this.date.getDay();
876 };
877
878
879 /**
880 * @return {goog.date.weekDay} The day of week, ISO style. 0 = Mon, 6 = Sun.
881 */
882 goog.date.Date.prototype.getIsoWeekday = function() {
883 return /** @type {goog.date.weekDay} */ ((this.getDay() + 6) % 7);
884 };
885
886
887 /**
888 * @return {number} The day of week according to firstDayOfWeek setting.
889 */
890 goog.date.Date.prototype.getWeekday = function() {
891 return (this.getIsoWeekday() - this.firstDayOfWeek_ + 7) % 7;
892 };
893
894
895 /**
896 * @return {number} The four digit year of date according to universal time.
897 */
898 goog.date.Date.prototype.getUTCFullYear = function() {
899 return this.date.getUTCFullYear();
900 };
901
902
903 /**
904 * @return {goog.date.month} The month of date according to universal time,
905 * 0 = Jan, 11 = Dec.
906 */
907 goog.date.Date.prototype.getUTCMonth = function() {
908 return /** @type {goog.date.month} */ (this.date.getUTCMonth());
909 };
910
911
912 /**
913 * @return {number} The date of month according to universal time.
914 */
915 goog.date.Date.prototype.getUTCDate = function() {
916 return this.date.getUTCDate();
917 };
918
919
920 /**
921 * @return {number} The day of week according to universal time, US style.
922 * 0 = Sun, 1 = Mon, 6 = Sat.
923 */
924 goog.date.Date.prototype.getUTCDay = function() {
925 return this.date.getDay();
926 };
927
928
929 /**
930 * @return {number} The hours value according to universal time.
931 */
932 goog.date.Date.prototype.getUTCHours = function() {
933 return this.date.getUTCHours();
934 };
935
936
937 /**
938 * @return {number} The minutes value according to universal time.
939 */
940 goog.date.Date.prototype.getUTCMinutes = function() {
941 return this.date.getUTCMinutes();
942 };
943
944
945 /**
946 * @return {goog.date.weekDay} The day of week according to universal time, ISO
947 * style. 0 = Mon, 6 = Sun.
948 */
949 goog.date.Date.prototype.getUTCIsoWeekday = function() {
950 return /** @type {goog.date.weekDay} */ ((this.date.getUTCDay() + 6) % 7);
951 };
952
953
954 /**
955 * @return {number} The day of week according to universal time and
956 * firstDayOfWeek setting.
957 */
958 goog.date.Date.prototype.getUTCWeekday = function() {
959 return (this.getUTCIsoWeekday() - this.firstDayOfWeek_ + 7) % 7;
960 };
961
962
963 /**
964 * @return {number} The first day of the week. 0 = Mon, 6 = Sun.
965 */
966 goog.date.Date.prototype.getFirstDayOfWeek = function() {
967 return this.firstDayOfWeek_;
968 };
969
970
971 /**
972 * @return {number} The cut off weekday used for week number calculations.
973 * 0 = Mon, 6 = Sun.
974 */
975 goog.date.Date.prototype.getFirstWeekCutOffDay = function() {
976 return this.firstWeekCutOffDay_;
977 };
978
979
980 /**
981 * @return {number} The number of days for the selected month.
982 */
983 goog.date.Date.prototype.getNumberOfDaysInMonth = function() {
984 return goog.date.getNumberOfDaysInMonth(this.getFullYear(), this.getMonth());
985 };
986
987
988 /**
989 * @return {number} The week number.
990 */
991 goog.date.Date.prototype.getWeekNumber = function() {
992 return goog.date.getWeekNumber(
993 this.getFullYear(), this.getMonth(), this.getDate(),
994 this.firstWeekCutOffDay_, this.firstDayOfWeek_);
995 };
996
997
998 /**
999 * @return {number} The day of year.
1000 */
1001 goog.date.Date.prototype.getDayOfYear = function() {
1002 var dayOfYear = this.getDate();
1003 var year = this.getFullYear();
1004 for (var m = this.getMonth() - 1; m >= 0; m--) {
1005 dayOfYear += goog.date.getNumberOfDaysInMonth(year, m);
1006 }
1007
1008 return dayOfYear;
1009 };
1010
1011
1012 /**
1013 * Returns timezone offset. The timezone offset is the delta in minutes between
1014 * UTC and your local time. E.g., UTC+10 returns -600. Daylight savings time
1015 * prevents this value from being constant.
1016 *
1017 * @return {number} The timezone offset.
1018 */
1019 goog.date.Date.prototype.getTimezoneOffset = function() {
1020 return this.date.getTimezoneOffset();
1021 };
1022
1023
1024 /**
1025 * Returns timezone offset as a string. Returns offset in [+-]HH:mm format or Z
1026 * for UTC.
1027 *
1028 * @return {string} The timezone offset as a string.
1029 */
1030 goog.date.Date.prototype.getTimezoneOffsetString = function() {
1031 var tz;
1032 var offset = this.getTimezoneOffset();
1033
1034 if (offset == 0) {
1035 tz = 'Z';
1036 } else {
1037 var n = Math.abs(offset) / 60;
1038 var h = Math.floor(n);
1039 var m = (n - h) * 60;
1040 tz = (offset > 0 ? '-' : '+') + goog.string.padNumber(h, 2) + ':' +
1041 goog.string.padNumber(m, 2);
1042 }
1043
1044 return tz;
1045 };
1046
1047
1048 /**
1049 * Sets the date.
1050 *
1051 * @param {goog.date.Date} date Date object to set date from.
1052 */
1053 goog.date.Date.prototype.set = function(date) {
1054 this.date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
1055 };
1056
1057
1058 /**
1059 * Sets the year part of the date.
1060 *
1061 * @param {number} year Four digit year.
1062 */
1063 goog.date.Date.prototype.setFullYear = function(year) {
1064 this.date.setFullYear(year);
1065 };
1066
1067
1068 /**
1069 * Alias for setFullYear.
1070 *
1071 * @param {number} year Four digit year.
1072 * @see #setFullYear
1073 */
1074 goog.date.Date.prototype.setYear = function(year) {
1075 this.setFullYear(year);
1076 };
1077
1078
1079 /**
1080 * Sets the month part of the date.
1081 *
1082 * TODO(nnaze): Update type to goog.date.month.
1083 *
1084 * @param {number} month The month, where 0 = Jan, 11 = Dec.
1085 */
1086 goog.date.Date.prototype.setMonth = function(month) {
1087 this.date.setMonth(month);
1088 };
1089
1090
1091 /**
1092 * Sets the day part of the date.
1093 *
1094 * @param {number} date The day part.
1095 */
1096 goog.date.Date.prototype.setDate = function(date) {
1097 this.date.setDate(date);
1098 };
1099
1100
1101 /**
1102 * Sets the value of the date object as expressed in the number of milliseconds
1103 * since 1 January 1970 00:00:00.
1104 *
1105 * @param {number} ms Number of milliseconds since 1 Jan 1970.
1106 */
1107 goog.date.Date.prototype.setTime = function(ms) {
1108 this.date.setTime(ms);
1109 };
1110
1111
1112 /**
1113 * Sets the year part of the date according to universal time.
1114 *
1115 * @param {number} year Four digit year.
1116 */
1117 goog.date.Date.prototype.setUTCFullYear = function(year) {
1118 this.date.setUTCFullYear(year);
1119 };
1120
1121
1122 /**
1123 * Sets the month part of the date according to universal time.
1124 *
1125 * @param {number} month The month, where 0 = Jan, 11 = Dec.
1126 */
1127 goog.date.Date.prototype.setUTCMonth = function(month) {
1128 this.date.setUTCMonth(month);
1129 };
1130
1131
1132 /**
1133 * Sets the day part of the date according to universal time.
1134 *
1135 * @param {number} date The UTC date.
1136 */
1137 goog.date.Date.prototype.setUTCDate = function(date) {
1138 this.date.setUTCDate(date);
1139 };
1140
1141
1142 /**
1143 * Sets the first day of week.
1144 *
1145 * @param {number} day 0 = Mon, 6 = Sun.
1146 */
1147 goog.date.Date.prototype.setFirstDayOfWeek = function(day) {
1148 this.firstDayOfWeek_ = day;
1149 };
1150
1151
1152 /**
1153 * Sets cut off weekday used for week number calculations. 0 = Mon, 6 = Sun.
1154 *
1155 * @param {number} day The cut off weekday.
1156 */
1157 goog.date.Date.prototype.setFirstWeekCutOffDay = function(day) {
1158 this.firstWeekCutOffDay_ = day;
1159 };
1160
1161
1162 /**
1163 * Performs date calculation by adding the supplied interval to the date.
1164 *
1165 * @param {goog.date.Interval} interval Date interval to add.
1166 */
1167 goog.date.Date.prototype.add = function(interval) {
1168 if (interval.years || interval.months) {
1169 // As months have different number of days adding a month to Jan 31 by just
1170 // setting the month would result in a date in early March rather than Feb
1171 // 28 or 29. Doing it this way overcomes that problem.
1172
1173 // adjust year and month, accounting for both directions
1174 var month = this.getMonth() + interval.months + interval.years * 12;
1175 var year = this.getYear() + Math.floor(month / 12);
1176 month %= 12;
1177 if (month < 0) {
1178 month += 12;
1179 }
1180
1181 var daysInTargetMonth = goog.date.getNumberOfDaysInMonth(year, month);
1182 var date = Math.min(daysInTargetMonth, this.getDate());
1183
1184 // avoid inadvertently causing rollovers to adjacent months
1185 this.setDate(1);
1186
1187 this.setFullYear(year);
1188 this.setMonth(month);
1189 this.setDate(date);
1190 }
1191
1192 if (interval.days) {
1193 // Convert the days to milliseconds and add it to the UNIX timestamp.
1194 // Taking noon helps to avoid 1 day error due to the daylight saving.
1195 var noon = new Date(this.getYear(), this.getMonth(), this.getDate(), 12);
1196 var result = new Date(noon.getTime() + interval.days * 86400000);
1197
1198 // Set date to 1 to prevent rollover caused by setting the year or month.
1199 this.setDate(1);
1200 this.setFullYear(result.getFullYear());
1201 this.setMonth(result.getMonth());
1202 this.setDate(result.getDate());
1203
1204 this.maybeFixDst_(result.getDate());
1205 }
1206 };
1207
1208
1209 /**
1210 * Returns ISO 8601 string representation of date.
1211 *
1212 * @param {boolean=} opt_verbose Whether the verbose format should be used
1213 * instead of the default compact one.
1214 * @param {boolean=} opt_tz Whether the timezone offset should be included
1215 * in the string.
1216 * @return {string} ISO 8601 string representation of date.
1217 */
1218 goog.date.Date.prototype.toIsoString = function(opt_verbose, opt_tz) {
1219 var str = [
1220 this.getFullYear(), goog.string.padNumber(this.getMonth() + 1, 2),
1221 goog.string.padNumber(this.getDate(), 2)
1222 ];
1223
1224 return str.join((opt_verbose) ? '-' : '') +
1225 (opt_tz ? this.getTimezoneOffsetString() : '');
1226 };
1227
1228
1229 /**
1230 * Returns ISO 8601 string representation of date according to universal time.
1231 *
1232 * @param {boolean=} opt_verbose Whether the verbose format should be used
1233 * instead of the default compact one.
1234 * @param {boolean=} opt_tz Whether the timezone offset should be included in
1235 * the string.
1236 * @return {string} ISO 8601 string representation of date according to
1237 * universal time.
1238 */
1239 goog.date.Date.prototype.toUTCIsoString = function(opt_verbose, opt_tz) {
1240 var str = [
1241 this.getUTCFullYear(), goog.string.padNumber(this.getUTCMonth() + 1, 2),
1242 goog.string.padNumber(this.getUTCDate(), 2)
1243 ];
1244
1245 return str.join((opt_verbose) ? '-' : '') + (opt_tz ? 'Z' : '');
1246 };
1247
1248
1249 /**
1250 * Tests whether given date is equal to this Date.
1251 * Note: This ignores units more precise than days (hours and below)
1252 * and also ignores timezone considerations.
1253 *
1254 * @param {goog.date.Date} other The date to compare.
1255 * @return {boolean} Whether the given date is equal to this one.
1256 */
1257 goog.date.Date.prototype.equals = function(other) {
1258 return !!(
1259 other && this.getYear() == other.getYear() &&
1260 this.getMonth() == other.getMonth() && this.getDate() == other.getDate());
1261 };
1262
1263
1264 /**
1265 * Overloaded toString method for object.
1266 * @return {string} ISO 8601 string representation of date.
1267 * @override
1268 */
1269 goog.date.Date.prototype.toString = function() {
1270 return this.toIsoString();
1271 };
1272
1273
1274 /**
1275 * Fixes date to account for daylight savings time in browsers that fail to do
1276 * so automatically.
1277 * @param {number} expected Expected date.
1278 * @private
1279 */
1280 goog.date.Date.prototype.maybeFixDst_ = function(expected) {
1281 if (this.getDate() != expected) {
1282 var dir = this.getDate() < expected ? 1 : -1;
1283 this.date.setUTCHours(this.date.getUTCHours() + dir);
1284 }
1285 };
1286
1287
1288 /**
1289 * @return {number} Value of wrapped date.
1290 * @override
1291 */
1292 goog.date.Date.prototype.valueOf = function() {
1293 return this.date.valueOf();
1294 };
1295
1296
1297 /**
1298 * Compares two dates. May be used as a sorting function.
1299 * @see goog.array.sort
1300 * @param {!goog.date.DateLike} date1 Date to compare.
1301 * @param {!goog.date.DateLike} date2 Date to compare.
1302 * @return {number} Comparison result. 0 if dates are the same, less than 0 if
1303 * date1 is earlier than date2, greater than 0 if date1 is later than date2.
1304 */
1305 goog.date.Date.compare = function(date1, date2) {
1306 return date1.getTime() - date2.getTime();
1307 };
1308
1309
1310 /**
1311 * Parses an ISO 8601 string as a {@code goog.date.Date}.
1312 * @param {string} formatted ISO 8601 string to parse.
1313 * @return {?goog.date.Date} Parsed date or null if parse fails.
1314 */
1315 goog.date.Date.fromIsoString = function(formatted) {
1316 var ret = new goog.date.Date(2000);
1317 return goog.date.setIso8601DateOnly_(ret, formatted) ? ret : null;
1318 };
1319
1320
1321
1322 /**
1323 * Class representing a date and time. Defaults to current date and time if none
1324 * is specified.
1325 *
1326 * Implements most methods of the native js Date object and can be used
1327 * interchangeably with it just as if goog.date.DateTime was a subclass of Date.
1328 *
1329 * @param {number|Object=} opt_year Four digit year or a date-like object. If
1330 * not set, the created object will contain the date determined by
1331 * goog.now().
1332 * @param {number=} opt_month Month, 0 = Jan, 11 = Dec.
1333 * @param {number=} opt_date Date of month, 1 - 31.
1334 * @param {number=} opt_hours Hours, 0 - 23.
1335 * @param {number=} opt_minutes Minutes, 0 - 59.
1336 * @param {number=} opt_seconds Seconds, 0 - 61.
1337 * @param {number=} opt_milliseconds Milliseconds, 0 - 999.
1338 * @constructor
1339 * @struct
1340 * @extends {goog.date.Date}
1341 */
1342 goog.date.DateTime = function(
1343 opt_year, opt_month, opt_date, opt_hours, opt_minutes, opt_seconds,
1344 opt_milliseconds) {
1345 if (goog.isNumber(opt_year)) {
1346 /** @override */
1347 this.date = new Date(
1348 opt_year, opt_month || 0, opt_date || 1, opt_hours || 0,
1349 opt_minutes || 0, opt_seconds || 0, opt_milliseconds || 0);
1350 } else {
1351 this.date = new Date(
1352 opt_year && opt_year.getTime ? opt_year.getTime() : goog.now());
1353 }
1354 };
1355 goog.inherits(goog.date.DateTime, goog.date.Date);
1356
1357
1358 /**
1359 * @param {number} timestamp Number of milliseconds since Epoch.
1360 * @return {!goog.date.DateTime}
1361 */
1362 goog.date.DateTime.fromTimestamp = function(timestamp) {
1363 var date = new goog.date.DateTime();
1364 date.setTime(timestamp);
1365 return date;
1366 };
1367
1368
1369 /**
1370 * Creates a DateTime from a datetime string expressed in RFC 822 format.
1371 *
1372 * @param {string} formatted A date or datetime expressed in RFC 822 format.
1373 * @return {goog.date.DateTime} Parsed date or null if parse fails.
1374 */
1375 goog.date.DateTime.fromRfc822String = function(formatted) {
1376 var date = new Date(formatted);
1377 return !isNaN(date.getTime()) ? new goog.date.DateTime(date) : null;
1378 };
1379
1380
1381 /**
1382 * Returns the hours part of the datetime.
1383 *
1384 * @return {number} An integer between 0 and 23, representing the hour.
1385 */
1386 goog.date.DateTime.prototype.getHours = function() {
1387 return this.date.getHours();
1388 };
1389
1390
1391 /**
1392 * Returns the minutes part of the datetime.
1393 *
1394 * @return {number} An integer between 0 and 59, representing the minutes.
1395 */
1396 goog.date.DateTime.prototype.getMinutes = function() {
1397 return this.date.getMinutes();
1398 };
1399
1400
1401 /**
1402 * Returns the seconds part of the datetime.
1403 *
1404 * @return {number} An integer between 0 and 59, representing the seconds.
1405 */
1406 goog.date.DateTime.prototype.getSeconds = function() {
1407 return this.date.getSeconds();
1408 };
1409
1410
1411 /**
1412 * Returns the milliseconds part of the datetime.
1413 *
1414 * @return {number} An integer between 0 and 999, representing the milliseconds.
1415 */
1416 goog.date.DateTime.prototype.getMilliseconds = function() {
1417 return this.date.getMilliseconds();
1418 };
1419
1420
1421 /**
1422 * Returns the day of week according to universal time, US style.
1423 *
1424 * @return {goog.date.weekDay} Day of week, 0 = Sun, 1 = Mon, 6 = Sat.
1425 * @override
1426 */
1427 goog.date.DateTime.prototype.getUTCDay = function() {
1428 return /** @type {goog.date.weekDay} */ (this.date.getUTCDay());
1429 };
1430
1431
1432 /**
1433 * Returns the hours part of the datetime according to universal time.
1434 *
1435 * @return {number} An integer between 0 and 23, representing the hour.
1436 * @override
1437 */
1438 goog.date.DateTime.prototype.getUTCHours = function() {
1439 return this.date.getUTCHours();
1440 };
1441
1442
1443 /**
1444 * Returns the minutes part of the datetime according to universal time.
1445 *
1446 * @return {number} An integer between 0 and 59, representing the minutes.
1447 * @override
1448 */
1449 goog.date.DateTime.prototype.getUTCMinutes = function() {
1450 return this.date.getUTCMinutes();
1451 };
1452
1453
1454 /**
1455 * Returns the seconds part of the datetime according to universal time.
1456 *
1457 * @return {number} An integer between 0 and 59, representing the seconds.
1458 */
1459 goog.date.DateTime.prototype.getUTCSeconds = function() {
1460 return this.date.getUTCSeconds();
1461 };
1462
1463
1464 /**
1465 * Returns the milliseconds part of the datetime according to universal time.
1466 *
1467 * @return {number} An integer between 0 and 999, representing the milliseconds.
1468 */
1469 goog.date.DateTime.prototype.getUTCMilliseconds = function() {
1470 return this.date.getUTCMilliseconds();
1471 };
1472
1473
1474 /**
1475 * Sets the hours part of the datetime.
1476 *
1477 * @param {number} hours An integer between 0 and 23, representing the hour.
1478 */
1479 goog.date.DateTime.prototype.setHours = function(hours) {
1480 this.date.setHours(hours);
1481 };
1482
1483
1484 /**
1485 * Sets the minutes part of the datetime.
1486 *
1487 * @param {number} minutes Integer between 0 and 59, representing the minutes.
1488 */
1489 goog.date.DateTime.prototype.setMinutes = function(minutes) {
1490 this.date.setMinutes(minutes);
1491 };
1492
1493
1494 /**
1495 * Sets the seconds part of the datetime.
1496 *
1497 * @param {number} seconds Integer between 0 and 59, representing the seconds.
1498 */
1499 goog.date.DateTime.prototype.setSeconds = function(seconds) {
1500 this.date.setSeconds(seconds);
1501 };
1502
1503
1504 /**
1505 * Sets the milliseconds part of the datetime.
1506 *
1507 * @param {number} ms Integer between 0 and 999, representing the milliseconds.
1508 */
1509 goog.date.DateTime.prototype.setMilliseconds = function(ms) {
1510 this.date.setMilliseconds(ms);
1511 };
1512
1513
1514 /**
1515 * Sets the hours part of the datetime according to universal time.
1516 *
1517 * @param {number} hours An integer between 0 and 23, representing the hour.
1518 */
1519 goog.date.DateTime.prototype.setUTCHours = function(hours) {
1520 this.date.setUTCHours(hours);
1521 };
1522
1523
1524 /**
1525 * Sets the minutes part of the datetime according to universal time.
1526 *
1527 * @param {number} minutes Integer between 0 and 59, representing the minutes.
1528 */
1529 goog.date.DateTime.prototype.setUTCMinutes = function(minutes) {
1530 this.date.setUTCMinutes(minutes);
1531 };
1532
1533
1534 /**
1535 * Sets the seconds part of the datetime according to universal time.
1536 *
1537 * @param {number} seconds Integer between 0 and 59, representing the seconds.
1538 */
1539 goog.date.DateTime.prototype.setUTCSeconds = function(seconds) {
1540 this.date.setUTCSeconds(seconds);
1541 };
1542
1543
1544 /**
1545 * Sets the seconds part of the datetime according to universal time.
1546 *
1547 * @param {number} ms Integer between 0 and 999, representing the milliseconds.
1548 */
1549 goog.date.DateTime.prototype.setUTCMilliseconds = function(ms) {
1550 this.date.setUTCMilliseconds(ms);
1551 };
1552
1553
1554 /**
1555 * @return {boolean} Whether the datetime is aligned to midnight.
1556 */
1557 goog.date.DateTime.prototype.isMidnight = function() {
1558 return this.getHours() == 0 && this.getMinutes() == 0 &&
1559 this.getSeconds() == 0 && this.getMilliseconds() == 0;
1560 };
1561
1562
1563 /**
1564 * Performs date calculation by adding the supplied interval to the date.
1565 *
1566 * @param {goog.date.Interval} interval Date interval to add.
1567 * @override
1568 */
1569 goog.date.DateTime.prototype.add = function(interval) {
1570 goog.date.Date.prototype.add.call(this, interval);
1571
1572 if (interval.hours) {
1573 this.setUTCHours(this.date.getUTCHours() + interval.hours);
1574 }
1575 if (interval.minutes) {
1576 this.setUTCMinutes(this.date.getUTCMinutes() + interval.minutes);
1577 }
1578 if (interval.seconds) {
1579 this.setUTCSeconds(this.date.getUTCSeconds() + interval.seconds);
1580 }
1581 };
1582
1583
1584 /**
1585 * Returns ISO 8601 string representation of date/time.
1586 *
1587 * @param {boolean=} opt_verbose Whether the verbose format should be used
1588 * instead of the default compact one.
1589 * @param {boolean=} opt_tz Whether the timezone offset should be included
1590 * in the string.
1591 * @return {string} ISO 8601 string representation of date/time.
1592 * @override
1593 */
1594 goog.date.DateTime.prototype.toIsoString = function(opt_verbose, opt_tz) {
1595 var dateString = goog.date.Date.prototype.toIsoString.call(this, opt_verbose);
1596
1597 if (opt_verbose) {
1598 return dateString + ' ' + goog.string.padNumber(this.getHours(), 2) + ':' +
1599 goog.string.padNumber(this.getMinutes(), 2) + ':' +
1600 goog.string.padNumber(this.getSeconds(), 2) +
1601 (opt_tz ? this.getTimezoneOffsetString() : '');
1602 }
1603
1604 return dateString + 'T' + goog.string.padNumber(this.getHours(), 2) +
1605 goog.string.padNumber(this.getMinutes(), 2) +
1606 goog.string.padNumber(this.getSeconds(), 2) +
1607 (opt_tz ? this.getTimezoneOffsetString() : '');
1608 };
1609
1610
1611 /**
1612 * Returns XML Schema 2 string representation of date/time.
1613 * The return value is also ISO 8601 compliant.
1614 *
1615 * @param {boolean=} opt_timezone Should the timezone offset be included in the
1616 * string?.
1617 * @return {string} XML Schema 2 string representation of date/time.
1618 */
1619 goog.date.DateTime.prototype.toXmlDateTime = function(opt_timezone) {
1620 return goog.date.Date.prototype.toIsoString.call(this, true) + 'T' +
1621 goog.string.padNumber(this.getHours(), 2) + ':' +
1622 goog.string.padNumber(this.getMinutes(), 2) + ':' +
1623 goog.string.padNumber(this.getSeconds(), 2) +
1624 (opt_timezone ? this.getTimezoneOffsetString() : '');
1625 };
1626
1627
1628 /**
1629 * Returns ISO 8601 string representation of date/time according to universal
1630 * time.
1631 *
1632 * @param {boolean=} opt_verbose Whether the opt_verbose format should be
1633 * returned instead of the default compact one.
1634 * @param {boolean=} opt_tz Whether the the timezone offset should be included
1635 * in the string.
1636 * @return {string} ISO 8601 string representation of date/time according to
1637 * universal time.
1638 * @override
1639 */
1640 goog.date.DateTime.prototype.toUTCIsoString = function(opt_verbose, opt_tz) {
1641 var dateStr = goog.date.Date.prototype.toUTCIsoString.call(this, opt_verbose);
1642
1643 if (opt_verbose) {
1644 return dateStr + ' ' + goog.string.padNumber(this.getUTCHours(), 2) + ':' +
1645 goog.string.padNumber(this.getUTCMinutes(), 2) + ':' +
1646 goog.string.padNumber(this.getUTCSeconds(), 2) + (opt_tz ? 'Z' : '');
1647 }
1648
1649 return dateStr + 'T' + goog.string.padNumber(this.getUTCHours(), 2) +
1650 goog.string.padNumber(this.getUTCMinutes(), 2) +
1651 goog.string.padNumber(this.getUTCSeconds(), 2) + (opt_tz ? 'Z' : '');
1652 };
1653
1654
1655 /**
1656 * Returns RFC 3339 string representation of datetime in UTC.
1657 *
1658 * @return {string} A UTC datetime expressed in RFC 3339 format.
1659 */
1660 goog.date.DateTime.prototype.toUTCRfc3339String = function() {
1661 var date = this.toUTCIsoString(true).replace(' ', 'T');
1662 var millis = this.getUTCMilliseconds();
1663 return (millis ? date + '.' + goog.string.padNumber(millis, 3) : date) + 'Z';
1664 };
1665
1666
1667 /**
1668 * Tests whether given datetime is exactly equal to this DateTime.
1669 *
1670 * @param {goog.date.Date} other The datetime to compare.
1671 * @return {boolean} Whether the given datetime is exactly equal to this one.
1672 * @override
1673 */
1674 goog.date.DateTime.prototype.equals = function(other) {
1675 return this.getTime() == other.getTime();
1676 };
1677
1678
1679 /**
1680 * Overloaded toString method for object.
1681 * @return {string} ISO 8601 string representation of date/time.
1682 * @override
1683 */
1684 goog.date.DateTime.prototype.toString = function() {
1685 return this.toIsoString();
1686 };
1687
1688
1689 /**
1690 * Generates time label for the datetime, e.g., '5:30 AM'.
1691 * By default this does not pad hours (e.g., to '05:30') and it does add
1692 * an am/pm suffix.
1693 * TODO(user): i18n -- hardcoding time format like this is bad. E.g., in CJK
1694 * locales, need Chinese characters for hour and minute units.
1695 * @param {boolean=} opt_padHours Whether to pad hours, e.g., '05:30' vs '5:30'.
1696 * @param {boolean=} opt_showAmPm Whether to show the 'am' and 'pm' suffix.
1697 * @param {boolean=} opt_omitZeroMinutes E.g., '5:00pm' becomes '5pm',
1698 * but '5:01pm' remains '5:01pm'.
1699 * @return {string} The time label.
1700 */
1701 goog.date.DateTime.prototype.toUsTimeString = function(
1702 opt_padHours, opt_showAmPm, opt_omitZeroMinutes) {
1703 var hours = this.getHours();
1704
1705 // show am/pm marker by default
1706 if (!goog.isDef(opt_showAmPm)) {
1707 opt_showAmPm = true;
1708 }
1709
1710 // 12pm
1711 var isPM = hours == 12;
1712
1713 // change from 1-24 to 1-12 basis
1714 if (hours > 12) {
1715 hours -= 12;
1716 isPM = true;
1717 }
1718
1719 // midnight is expressed as "12am", but if am/pm marker omitted, keep as '0'
1720 if (hours == 0 && opt_showAmPm) {
1721 hours = 12;
1722 }
1723
1724 var label = opt_padHours ? goog.string.padNumber(hours, 2) : String(hours);
1725 var minutes = this.getMinutes();
1726 if (!opt_omitZeroMinutes || minutes > 0) {
1727 label += ':' + goog.string.padNumber(minutes, 2);
1728 }
1729
1730 // by default, show am/pm suffix
1731 if (opt_showAmPm) {
1732 label += isPM ? ' PM' : ' AM';
1733 }
1734 return label;
1735 };
1736
1737
1738 /**
1739 * Generates time label for the datetime in standard ISO 24-hour time format.
1740 * E.g., '06:00:00' or '23:30:15'.
1741 * @param {boolean=} opt_showSeconds Whether to shows seconds. Defaults to TRUE.
1742 * @return {string} The time label.
1743 */
1744 goog.date.DateTime.prototype.toIsoTimeString = function(opt_showSeconds) {
1745 var hours = this.getHours();
1746 var label = goog.string.padNumber(hours, 2) + ':' +
1747 goog.string.padNumber(this.getMinutes(), 2);
1748 if (!goog.isDef(opt_showSeconds) || opt_showSeconds) {
1749 label += ':' + goog.string.padNumber(this.getSeconds(), 2);
1750 }
1751 return label;
1752 };
1753
1754
1755 /**
1756 * @return {!goog.date.DateTime} A clone of the datetime object.
1757 * @override
1758 */
1759 goog.date.DateTime.prototype.clone = function() {
1760 var date = new goog.date.DateTime(this.date);
1761 date.setFirstDayOfWeek(this.getFirstDayOfWeek());
1762 date.setFirstWeekCutOffDay(this.getFirstWeekCutOffDay());
1763 return date;
1764 };
1765
1766
1767 /**
1768 * Parses an ISO 8601 string as a {@code goog.date.DateTime}.
1769 * @param {string} formatted ISO 8601 string to parse.
1770 * @return {?goog.date.DateTime} Parsed date or null if parse fails.
1771 * @override
1772 */
1773 goog.date.DateTime.fromIsoString = function(formatted) {
1774 var ret = new goog.date.DateTime(2000);
1775 return goog.date.setIso8601DateTime(ret, formatted) ? ret : null;
1776 };