date.js 48 KB

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