date.js 127 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339
  1. /**
  2. * @overview datejs
  3. * @version 1.0.0-rc3
  4. * @author Gregory Wild-Smith <gregory@wild-smith.com>
  5. * @copyright 2014 Gregory Wild-Smith
  6. * @license MIT
  7. * @homepage https://github.com/abritinthebay/datejs
  8. */(function () {
  9. var $D = Date;
  10. var lang = Date.CultureStrings ? Date.CultureStrings.lang : null;
  11. var loggedKeys = {}; // for debug purposes.
  12. var getText = {
  13. getFromKey: function (key, countryCode) {
  14. var output;
  15. if (Date.CultureStrings && Date.CultureStrings[countryCode] && Date.CultureStrings[countryCode][key]) {
  16. output = Date.CultureStrings[countryCode][key];
  17. } else {
  18. output = getText.buildFromDefault(key);
  19. }
  20. if (key.charAt(0) === "/") { // Assume it's a regex
  21. output = getText.buildFromRegex(key, countryCode);
  22. }
  23. return output;
  24. },
  25. getFromObjectValues: function (obj, countryCode) {
  26. var key, output = {};
  27. for(key in obj) {
  28. if (obj.hasOwnProperty(key)) {
  29. output[key] = getText.getFromKey(obj[key], countryCode);
  30. }
  31. }
  32. return output;
  33. },
  34. getFromObjectKeys: function (obj, countryCode) {
  35. var key, output = {};
  36. for(key in obj) {
  37. if (obj.hasOwnProperty(key)) {
  38. output[getText.getFromKey(key, countryCode)] = obj[key];
  39. }
  40. }
  41. return output;
  42. },
  43. getFromArray: function (arr, countryCode) {
  44. var output = [];
  45. for (var i=0; i < arr.length; i++){
  46. if (i in arr) {
  47. output[i] = getText.getFromKey(arr[i], countryCode);
  48. }
  49. }
  50. return output;
  51. },
  52. buildFromDefault: function (key) {
  53. var output, length, split, last;
  54. switch(key) {
  55. case "name":
  56. output = "en-US";
  57. break;
  58. case "englishName":
  59. output = "English (United States)";
  60. break;
  61. case "nativeName":
  62. output = "English (United States)";
  63. break;
  64. case "twoDigitYearMax":
  65. output = 2049;
  66. break;
  67. case "firstDayOfWeek":
  68. output = 0;
  69. break;
  70. default:
  71. output = key;
  72. split = key.split("_");
  73. length = split.length;
  74. if (length > 1 && key.charAt(0) !== "/") {
  75. // if the key isn't a regex and it has a split.
  76. last = split[(length - 1)].toLowerCase();
  77. if (last === "initial" || last === "abbr") {
  78. output = split[0];
  79. }
  80. }
  81. break;
  82. }
  83. return output;
  84. },
  85. buildFromRegex: function (key, countryCode) {
  86. var output;
  87. if (Date.CultureStrings && Date.CultureStrings[countryCode] && Date.CultureStrings[countryCode][key]) {
  88. output = new RegExp(Date.CultureStrings[countryCode][key], "i");
  89. } else {
  90. output = new RegExp(key.replace(new RegExp("/", "g"),""), "i");
  91. }
  92. return output;
  93. }
  94. };
  95. var shallowMerge = function (obj1, obj2) {
  96. for (var attrname in obj2) {
  97. if (obj2.hasOwnProperty(attrname)) {
  98. obj1[attrname] = obj2[attrname];
  99. }
  100. }
  101. };
  102. var __ = function (key, language) {
  103. var countryCode = (language) ? language : lang;
  104. loggedKeys[key] = key;
  105. if (typeof key === "object") {
  106. if (key instanceof Array) {
  107. return getText.getFromArray(key, countryCode);
  108. } else {
  109. return getText.getFromObjectKeys(key, countryCode);
  110. }
  111. } else {
  112. return getText.getFromKey(key, countryCode);
  113. }
  114. };
  115. var loadI18nScript = function (code) {
  116. // paatterned after jQuery's getScript.
  117. var url = Date.Config.i18n + code + ".js";
  118. var head = document.getElementsByTagName("head")[0] || document.documentElement;
  119. var script = document.createElement("script");
  120. script.src = url;
  121. var completed = false;
  122. var events = {
  123. done: function (){} // placeholder function
  124. };
  125. // Attach handlers for all browsers
  126. script.onload = script.onreadystatechange = function() {
  127. if ( !completed && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) {
  128. events.done();
  129. head.removeChild(script);
  130. }
  131. };
  132. setTimeout(function() {
  133. head.insertBefore(script, head.firstChild);
  134. }, 0); // allows return to execute first
  135. return {
  136. done: function (cb) {
  137. events.done = function() {
  138. if (cb) {
  139. setTimeout(cb,0);
  140. }
  141. };
  142. }
  143. };
  144. };
  145. var buildInfo = {
  146. buildFromMethodHash: function (obj) {
  147. var key;
  148. for(key in obj) {
  149. if (obj.hasOwnProperty(key)) {
  150. obj[key] = buildInfo[obj[key]]();
  151. }
  152. }
  153. return obj;
  154. },
  155. timeZoneDST: function () {
  156. var DST = {
  157. "CHADT": "+1345",
  158. "NZDT": "+1300",
  159. "AEDT": "+1100",
  160. "ACDT": "+1030",
  161. "AZST": "+0500",
  162. "IRDT": "+0430",
  163. "EEST": "+0300",
  164. "CEST": "+0200",
  165. "BST": "+0100",
  166. "PMDT": "-0200",
  167. "ADT": "-0300",
  168. "NDT": "-0230",
  169. "EDT": "-0400",
  170. "CDT": "-0500",
  171. "MDT": "-0600",
  172. "PDT": "-0700",
  173. "AKDT": "-0800",
  174. "HADT": "-0900"
  175. };
  176. return __(DST);
  177. },
  178. timeZoneStandard: function () {
  179. var standard = {
  180. "LINT": "+1400",
  181. "TOT": "+1300",
  182. "CHAST": "+1245",
  183. "NZST": "+1200",
  184. "NFT": "+1130",
  185. "SBT": "+1100",
  186. "AEST": "+1000",
  187. "ACST": "+0930",
  188. "JST": "+0900",
  189. "CWST": "+0845",
  190. "CT": "+0800",
  191. "ICT": "+0700",
  192. "MMT": "+0630",
  193. "BST": "+0600",
  194. "NPT": "+0545",
  195. "IST": "+0530",
  196. "PKT": "+0500",
  197. "AFT": "+0430",
  198. "MSK": "+0400",
  199. "IRST": "+0330",
  200. "FET": "+0300",
  201. "EET": "+0200",
  202. "CET": "+0100",
  203. "GMT": "+0000",
  204. "UTC": "+0000",
  205. "CVT": "-0100",
  206. "GST": "-0200",
  207. "BRT": "-0300",
  208. "NST": "-0330",
  209. "AST": "-0400",
  210. "EST": "-0500",
  211. "CST": "-0600",
  212. "MST": "-0700",
  213. "PST": "-0800",
  214. "AKST": "-0900",
  215. "MIT": "-0930",
  216. "HST": "-1000",
  217. "SST": "-1100",
  218. "BIT": "-1200"
  219. };
  220. return __(standard);
  221. },
  222. timeZones: function (data) {
  223. var zone;
  224. data.timezones = [];
  225. for (zone in data.abbreviatedTimeZoneStandard) {
  226. if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) {
  227. data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]});
  228. }
  229. }
  230. for (zone in data.abbreviatedTimeZoneDST) {
  231. if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) {
  232. data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone], dst: true});
  233. }
  234. }
  235. return data.timezones;
  236. },
  237. days: function () {
  238. return __(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]);
  239. },
  240. dayAbbr: function () {
  241. return __(["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]);
  242. },
  243. dayShortNames: function () {
  244. return __(["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"]);
  245. },
  246. dayFirstLetters: function () {
  247. return __(["S_Sun_Initial", "M_Mon_Initial", "T_Tues_Initial", "W_Wed_Initial", "T_Thu_Initial", "F_Fri_Initial", "S_Sat_Initial"]);
  248. },
  249. months: function () {
  250. return __(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]);
  251. },
  252. monthAbbr: function () {
  253. return __(["Jan_Abbr", "Feb_Abbr", "Mar_Abbr", "Apr_Abbr", "May_Abbr", "Jun_Abbr", "Jul_Abbr", "Aug_Abbr", "Sep_Abbr", "Oct_Abbr", "Nov_Abbr", "Dec_Abbr"]);
  254. },
  255. formatPatterns: function () {
  256. return getText.getFromObjectValues({
  257. shortDate: "M/d/yyyy",
  258. longDate: "dddd, MMMM dd, yyyy",
  259. shortTime: "h:mm tt",
  260. longTime: "h:mm:ss tt",
  261. fullDateTime: "dddd, MMMM dd, yyyy h:mm:ss tt",
  262. sortableDateTime: "yyyy-MM-ddTHH:mm:ss",
  263. universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ",
  264. rfc1123: "ddd, dd MMM yyyy HH:mm:ss",
  265. monthDay: "MMMM dd",
  266. yearMonth: "MMMM, yyyy"
  267. }, Date.i18n.currentLanguage());
  268. },
  269. regex: function () {
  270. return getText.getFromObjectValues({
  271. inTheMorning: "/( in the )(morn(ing)?)\\b/",
  272. thisMorning: "/(this )(morn(ing)?)\\b/",
  273. amThisMorning: "/(\b\\d(am)? )(this )(morn(ing)?)/",
  274. inTheEvening: "/( in the )(even(ing)?)\\b/",
  275. thisEvening: "/(this )(even(ing)?)\\b/",
  276. pmThisEvening: "/(\b\\d(pm)? )(this )(even(ing)?)/",
  277. jan: "/jan(uary)?/",
  278. feb: "/feb(ruary)?/",
  279. mar: "/mar(ch)?/",
  280. apr: "/apr(il)?/",
  281. may: "/may/",
  282. jun: "/jun(e)?/",
  283. jul: "/jul(y)?/",
  284. aug: "/aug(ust)?/",
  285. sep: "/sep(t(ember)?)?/",
  286. oct: "/oct(ober)?/",
  287. nov: "/nov(ember)?/",
  288. dec: "/dec(ember)?/",
  289. sun: "/^su(n(day)?)?/",
  290. mon: "/^mo(n(day)?)?/",
  291. tue: "/^tu(e(s(day)?)?)?/",
  292. wed: "/^we(d(nesday)?)?/",
  293. thu: "/^th(u(r(s(day)?)?)?)?/",
  294. fri: "/fr(i(day)?)?/",
  295. sat: "/^sa(t(urday)?)?/",
  296. future: "/^next/",
  297. past: "/^last|past|prev(ious)?/",
  298. add: "/^(\\+|aft(er)?|from|hence)/",
  299. subtract: "/^(\\-|bef(ore)?|ago)/",
  300. yesterday: "/^yes(terday)?/",
  301. today: "/^t(od(ay)?)?/",
  302. tomorrow: "/^tom(orrow)?/",
  303. now: "/^n(ow)?/",
  304. millisecond: "/^ms|milli(second)?s?/",
  305. second: "/^sec(ond)?s?/",
  306. minute: "/^mn|min(ute)?s?/",
  307. hour: "/^h(our)?s?/",
  308. week: "/^w(eek)?s?/",
  309. month: "/^m(onth)?s?/",
  310. day: "/^d(ay)?s?/",
  311. year: "/^y(ear)?s?/",
  312. shortMeridian: "/^(a|p)/",
  313. longMeridian: "/^(a\\.?m?\\.?|p\\.?m?\\.?)/",
  314. timezone: "/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/",
  315. ordinalSuffix: "/^\\s*(st|nd|rd|th)/",
  316. timeContext: "/^\\s*(\\:|a(?!u|p)|p)/"
  317. }, Date.i18n.currentLanguage());
  318. }
  319. };
  320. var CultureInfo = function () {
  321. var info = getText.getFromObjectValues({
  322. name: "name",
  323. englishName: "englishName",
  324. nativeName: "nativeName",
  325. amDesignator: "AM",
  326. pmDesignator: "PM",
  327. firstDayOfWeek: "firstDayOfWeek",
  328. twoDigitYearMax: "twoDigitYearMax",
  329. dateElementOrder: "mdy"
  330. }, Date.i18n.currentLanguage());
  331. var constructedInfo = buildInfo.buildFromMethodHash({
  332. dayNames: "days",
  333. abbreviatedDayNames: "dayAbbr",
  334. shortestDayNames: "dayShortNames",
  335. firstLetterDayNames: "dayFirstLetters",
  336. monthNames: "months",
  337. abbreviatedMonthNames: "monthAbbr",
  338. formatPatterns: "formatPatterns",
  339. regexPatterns: "regex",
  340. abbreviatedTimeZoneDST: "timeZoneDST",
  341. abbreviatedTimeZoneStandard: "timeZoneStandard"
  342. });
  343. shallowMerge(info, constructedInfo);
  344. buildInfo.timeZones(info);
  345. return info;
  346. };
  347. $D.i18n = {
  348. __: function (key, lang) {
  349. return __(key, lang);
  350. },
  351. currentLanguage: function () {
  352. return lang || "en-US";
  353. },
  354. setLanguage: function (code, force, cb) {
  355. var async = false;
  356. if (force || code === "en-US" || (!!Date.CultureStrings && !!Date.CultureStrings[code])) {
  357. lang = code;
  358. Date.CultureStrings = Date.CultureStrings || {};
  359. Date.CultureStrings.lang = code;
  360. Date.CultureInfo = new CultureInfo();
  361. } else {
  362. if (!(!!Date.CultureStrings && !!Date.CultureStrings[code])) {
  363. if (typeof exports !== "undefined" && this.exports !== exports) {
  364. // we're in a Node enviroment, load it using require
  365. try {
  366. require("../i18n/" + code + ".js");
  367. lang = code;
  368. Date.CultureStrings.lang = code;
  369. Date.CultureInfo = new CultureInfo();
  370. } catch (e) {
  371. // var str = "The language for '" + code + "' could not be loaded by Node. It likely does not exist.";
  372. throw new Error("The DateJS IETF language tag '" + code + "' could not be loaded by Node. It likely does not exist.");
  373. }
  374. } else if (Date.Config && Date.Config.i18n) {
  375. // we know the location of the files, so lets load them
  376. async = true;
  377. loadI18nScript(code).done(function(){
  378. lang = code;
  379. Date.CultureStrings = Date.CultureStrings || {};
  380. Date.CultureStrings.lang = code;
  381. Date.CultureInfo = new CultureInfo();
  382. $D.Parsing.Normalizer.buildReplaceData(); // because this is async
  383. if ($D.Grammar) {
  384. $D.Grammar.buildGrammarFormats(); // so we can parse those strings...
  385. }
  386. if (cb) {
  387. setTimeout(cb,0);
  388. }
  389. });
  390. } else {
  391. Date.console.error("The DateJS IETF language tag '" + code + "' is not available and has not been loaded.");
  392. return false;
  393. }
  394. }
  395. }
  396. $D.Parsing.Normalizer.buildReplaceData(); // rebuild normalizer strings
  397. if ($D.Grammar) {
  398. $D.Grammar.buildGrammarFormats(); // so we can parse those strings...
  399. }
  400. if (!async && cb) {
  401. setTimeout(cb,0);
  402. }
  403. },
  404. getLoggedKeys: function () {
  405. return loggedKeys;
  406. },
  407. updateCultureInfo: function () {
  408. Date.CultureInfo = new CultureInfo();
  409. }
  410. };
  411. $D.i18n.updateCultureInfo(); // run automatically
  412. }());
  413. (function () {
  414. var $D = Date,
  415. $P = $D.prototype,
  416. p = function (s, l) {
  417. if (!l) {
  418. l = 2;
  419. }
  420. return ("000" + s).slice(l * -1);
  421. };
  422. if (typeof window !== "undefined" && typeof window.console !== "undefined" && typeof window.console.log !== "undefined") {
  423. $D.console = console; // used only to raise non-critical errors if available
  424. } else {
  425. // set mock so we don't give errors.
  426. $D.console = {
  427. log: function(){},
  428. error: function(){}
  429. };
  430. }
  431. $D.Config = $D.Config || {};
  432. $D.initOverloads = function() {
  433. /**
  434. * Overload of Date.now. Allows an alternate call for Date.now where it returns the
  435. * current Date as an object rather than just milliseconds since the Unix Epoch.
  436. *
  437. * Also provides an implementation of now() for browsers (IE<9) that don't have it.
  438. *
  439. * Backwards compatible so with work with either:
  440. * Date.now() [returns ms]
  441. * or
  442. * Date.now(true) [returns Date]
  443. */
  444. if (!$D.now) {
  445. $D._now = function now() {
  446. return new Date().getTime();
  447. };
  448. } else if (!$D._now) {
  449. $D._now = $D.now;
  450. }
  451. $D.now = function (returnObj) {
  452. if (returnObj) {
  453. return $D.present();
  454. } else {
  455. return $D._now();
  456. }
  457. };
  458. if ( !$P.toISOString ) {
  459. $P.toISOString = function() {
  460. return this.getUTCFullYear() +
  461. "-" + p(this.getUTCMonth() + 1) +
  462. "-" + p(this.getUTCDate()) +
  463. "T" + p(this.getUTCHours()) +
  464. ":" + p(this.getUTCMinutes()) +
  465. ":" + p(this.getUTCSeconds()) +
  466. "." + String( (this.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) +
  467. "Z";
  468. };
  469. }
  470. // private
  471. if ( $P._toString === undefined ){
  472. $P._toString = $P.toString;
  473. }
  474. };
  475. $D.initOverloads();
  476. /**
  477. * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM).
  478. * @return {Date} The current date.
  479. */
  480. $D.today = function () {
  481. return new Date().clearTime();
  482. };
  483. /**
  484. * Gets a date that is set to the current date and time (same as new Date, but chainable)
  485. * @return {Date} The current date.
  486. */
  487. $D.present = function () {
  488. return new Date();
  489. };
  490. /**
  491. * Compares the first date to the second date and returns an number indication of their relative values.
  492. * @param {Date} First Date object to compare [Required].
  493. * @param {Date} Second Date object to compare to [Required].
  494. * @return {Number} -1 = date1 is lessthan date2. 0 = values are equal. 1 = date1 is greaterthan date2.
  495. */
  496. $D.compare = function (date1, date2) {
  497. if (isNaN(date1) || isNaN(date2)) {
  498. throw new Error(date1 + " - " + date2);
  499. } else if (date1 instanceof Date && date2 instanceof Date) {
  500. return (date1 < date2) ? -1 : (date1 > date2) ? 1 : 0;
  501. } else {
  502. throw new TypeError(date1 + " - " + date2);
  503. }
  504. };
  505. /**
  506. * Compares the first Date object to the second Date object and returns true if they are equal.
  507. * @param {Date} First Date object to compare [Required]
  508. * @param {Date} Second Date object to compare to [Required]
  509. * @return {Boolean} true if dates are equal. false if they are not equal.
  510. */
  511. $D.equals = function (date1, date2) {
  512. return (date1.compareTo(date2) === 0);
  513. };
  514. /**
  515. * Gets the language appropriate day name when given the day number(0-6)
  516. * eg - 0 == Sunday
  517. * @return {String} The day name
  518. */
  519. $D.getDayName = function (n) {
  520. return Date.CultureInfo.dayNames[n];
  521. };
  522. /**
  523. * Gets the day number (0-6) if given a CultureInfo specific string which is a valid dayName, abbreviatedDayName or shortestDayName (two char).
  524. * @param {String} The name of the day (eg. "Monday, "Mon", "tuesday", "tue", "We", "we").
  525. * @return {Number} The day number
  526. */
  527. $D.getDayNumberFromName = function (name) {
  528. var n = Date.CultureInfo.dayNames, m = Date.CultureInfo.abbreviatedDayNames, o = Date.CultureInfo.shortestDayNames, s = name.toLowerCase();
  529. for (var i = 0; i < n.length; i++) {
  530. if (n[i].toLowerCase() === s || m[i].toLowerCase() === s || o[i].toLowerCase() === s) {
  531. return i;
  532. }
  533. }
  534. return -1;
  535. };
  536. /**
  537. * Gets the month number (0-11) if given a Culture Info specific string which is a valid monthName or abbreviatedMonthName.
  538. * @param {String} The name of the month (eg. "February, "Feb", "october", "oct").
  539. * @return {Number} The day number
  540. */
  541. $D.getMonthNumberFromName = function (name) {
  542. var n = Date.CultureInfo.monthNames, m = Date.CultureInfo.abbreviatedMonthNames, s = name.toLowerCase();
  543. for (var i = 0; i < n.length; i++) {
  544. if (n[i].toLowerCase() === s || m[i].toLowerCase() === s) {
  545. return i;
  546. }
  547. }
  548. return -1;
  549. };
  550. /**
  551. * Gets the language appropriate month name when given the month number(0-11)
  552. * eg - 0 == January
  553. * @return {String} The month name
  554. */
  555. $D.getMonthName = function (n) {
  556. return Date.CultureInfo.monthNames[n];
  557. };
  558. /**
  559. * Determines if the current date instance is within a LeapYear.
  560. * @param {Number} The year.
  561. * @return {Boolean} true if date is within a LeapYear, otherwise false.
  562. */
  563. $D.isLeapYear = function (year) {
  564. return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);
  565. };
  566. /**
  567. * Gets the number of days in the month, given a year and month value. Automatically corrects for LeapYear.
  568. * @param {Number} The year.
  569. * @param {Number} The month (0-11).
  570. * @return {Number} The number of days in the month.
  571. */
  572. $D.getDaysInMonth = function (year, month) {
  573. if (!month && $D.validateMonth(year)) {
  574. month = year;
  575. year = Date.today().getFullYear();
  576. }
  577. return [31, ($D.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
  578. };
  579. $P.getDaysInMonth = function () {
  580. return $D.getDaysInMonth(this.getFullYear(), this.getMonth());
  581. };
  582. $D.getTimezoneAbbreviation = function (offset, dst) {
  583. var p, n = (dst || false) ? Date.CultureInfo.abbreviatedTimeZoneDST : Date.CultureInfo.abbreviatedTimeZoneStandard;
  584. for (p in n) {
  585. if (n.hasOwnProperty(p)) {
  586. if (n[p] === offset) {
  587. return p;
  588. }
  589. }
  590. }
  591. return null;
  592. };
  593. $D.getTimezoneOffset = function (name, dst) {
  594. var i, a =[], z = Date.CultureInfo.timezones;
  595. if (!name) { name = (new Date()).getTimezone();}
  596. for (i = 0; i < z.length; i++) {
  597. if (z[i].name === name.toUpperCase()) {
  598. a.push(i);
  599. }
  600. }
  601. if (!z[a[0]]) {
  602. return null;
  603. }
  604. if (a.length === 1 || !dst) {
  605. return z[a[0]].offset;
  606. } else {
  607. for (i=0; i < a.length; i++) {
  608. if (z[a[i]].dst) {
  609. return z[a[i]].offset;
  610. }
  611. }
  612. }
  613. };
  614. $D.getQuarter = function (d) {
  615. d = d || new Date(); // If no date supplied, use today
  616. var q = [1,2,3,4];
  617. return q[Math.floor(d.getMonth() / 3)]; // ~~~ is a bitwise op. Faster than Math.floor
  618. };
  619. $D.getDaysLeftInQuarter = function (d) {
  620. d = d || new Date();
  621. var qEnd = new Date(d);
  622. qEnd.setMonth(qEnd.getMonth() + 3 - qEnd.getMonth() % 3, 0);
  623. return Math.floor((qEnd - d) / 8.64e7);
  624. };
  625. // private
  626. var validate = function (n, min, max, name) {
  627. name = name ? name : "Object";
  628. if (typeof n === "undefined") {
  629. return false;
  630. } else if (typeof n !== "number") {
  631. throw new TypeError(n + " is not a Number.");
  632. } else if (n < min || n > max) {
  633. // As failing validation is *not* an exceptional circumstance
  634. // lets not throw a RangeError Exception here.
  635. // It's semantically correct but it's not sensible.
  636. return false;
  637. }
  638. return true;
  639. };
  640. /**
  641. * Validates the number is within an acceptable range for milliseconds [0-999].
  642. * @param {Number} The number to check if within range.
  643. * @return {Boolean} true if within range, otherwise false.
  644. */
  645. $D.validateMillisecond = function (value) {
  646. return validate(value, 0, 999, "millisecond");
  647. };
  648. /**
  649. * Validates the number is within an acceptable range for seconds [0-59].
  650. * @param {Number} The number to check if within range.
  651. * @return {Boolean} true if within range, otherwise false.
  652. */
  653. $D.validateSecond = function (value) {
  654. return validate(value, 0, 59, "second");
  655. };
  656. /**
  657. * Validates the number is within an acceptable range for minutes [0-59].
  658. * @param {Number} The number to check if within range.
  659. * @return {Boolean} true if within range, otherwise false.
  660. */
  661. $D.validateMinute = function (value) {
  662. return validate(value, 0, 59, "minute");
  663. };
  664. /**
  665. * Validates the number is within an acceptable range for hours [0-23].
  666. * @param {Number} The number to check if within range.
  667. * @return {Boolean} true if within range, otherwise false.
  668. */
  669. $D.validateHour = function (value) {
  670. return validate(value, 0, 23, "hour");
  671. };
  672. /**
  673. * Validates the number is within an acceptable range for the days in a month [0-MaxDaysInMonth].
  674. * @param {Number} The number to check if within range.
  675. * @return {Boolean} true if within range, otherwise false.
  676. */
  677. $D.validateDay = function (value, year, month) {
  678. if (year === undefined || year === null || month === undefined || month === null) { return false;}
  679. return validate(value, 1, $D.getDaysInMonth(year, month), "day");
  680. };
  681. /**
  682. * Validates the number is within an acceptable range for months [0-11].
  683. * @param {Number} The number to check if within range.
  684. * @return {Boolean} true if within range, otherwise false.
  685. */
  686. $D.validateWeek = function (value) {
  687. return validate(value, 0, 53, "week");
  688. };
  689. /**
  690. * Validates the number is within an acceptable range for months [0-11].
  691. * @param {Number} The number to check if within range.
  692. * @return {Boolean} true if within range, otherwise false.
  693. */
  694. $D.validateMonth = function (value) {
  695. return validate(value, 0, 11, "month");
  696. };
  697. /**
  698. * Validates the number is within an acceptable range for years.
  699. * @param {Number} The number to check if within range.
  700. * @return {Boolean} true if within range, otherwise false.
  701. */
  702. $D.validateYear = function (value) {
  703. /**
  704. * Per ECMAScript spec the range of times supported by Date objects is
  705. * exactly -100,000,000 days to +100,000,000 days measured relative to
  706. * midnight at the beginning of 01 January, 1970 UTC.
  707. * This gives a range of 8,640,000,000,000,000 milliseconds to either
  708. * side of 01 January, 1970 UTC.
  709. *
  710. * Earliest possible date: Tue, 20 Apr 271,822 B.C. 00:00:00 UTC
  711. * Latest possible date: Sat, 13 Sep 275,760 00:00:00 UTC
  712. */
  713. return validate(value, -271822, 275760, "year");
  714. };
  715. $D.validateTimezone = function(value) {
  716. var timezones = {"ACDT":1,"ACST":1,"ACT":1,"ADT":1,"AEDT":1,"AEST":1,"AFT":1,"AKDT":1,"AKST":1,"AMST":1,"AMT":1,"ART":1,"AST":1,"AWDT":1,"AWST":1,"AZOST":1,"AZT":1,"BDT":1,"BIOT":1,"BIT":1,"BOT":1,"BRT":1,"BST":1,"BTT":1,"CAT":1,"CCT":1,"CDT":1,"CEDT":1,"CEST":1,"CET":1,"CHADT":1,"CHAST":1,"CHOT":1,"ChST":1,"CHUT":1,"CIST":1,"CIT":1,"CKT":1,"CLST":1,"CLT":1,"COST":1,"COT":1,"CST":1,"CT":1,"CVT":1,"CWST":1,"CXT":1,"DAVT":1,"DDUT":1,"DFT":1,"EASST":1,"EAST":1,"EAT":1,"ECT":1,"EDT":1,"EEDT":1,"EEST":1,"EET":1,"EGST":1,"EGT":1,"EIT":1,"EST":1,"FET":1,"FJT":1,"FKST":1,"FKT":1,"FNT":1,"GALT":1,"GAMT":1,"GET":1,"GFT":1,"GILT":1,"GIT":1,"GMT":1,"GST":1,"GYT":1,"HADT":1,"HAEC":1,"HAST":1,"HKT":1,"HMT":1,"HOVT":1,"HST":1,"ICT":1,"IDT":1,"IOT":1,"IRDT":1,"IRKT":1,"IRST":1,"IST":1,"JST":1,"KGT":1,"KOST":1,"KRAT":1,"KST":1,"LHST":1,"LINT":1,"MAGT":1,"MART":1,"MAWT":1,"MDT":1,"MET":1,"MEST":1,"MHT":1,"MIST":1,"MIT":1,"MMT":1,"MSK":1,"MST":1,"MUT":1,"MVT":1,"MYT":1,"NCT":1,"NDT":1,"NFT":1,"NPT":1,"NST":1,"NT":1,"NUT":1,"NZDT":1,"NZST":1,"OMST":1,"ORAT":1,"PDT":1,"PET":1,"PETT":1,"PGT":1,"PHOT":1,"PHT":1,"PKT":1,"PMDT":1,"PMST":1,"PONT":1,"PST":1,"PYST":1,"PYT":1,"RET":1,"ROTT":1,"SAKT":1,"SAMT":1,"SAST":1,"SBT":1,"SCT":1,"SGT":1,"SLST":1,"SRT":1,"SST":1,"SYOT":1,"TAHT":1,"THA":1,"TFT":1,"TJT":1,"TKT":1,"TLT":1,"TMT":1,"TOT":1,"TVT":1,"UCT":1,"ULAT":1,"UTC":1,"UYST":1,"UYT":1,"UZT":1,"VET":1,"VLAT":1,"VOLT":1,"VOST":1,"VUT":1,"WAKT":1,"WAST":1,"WAT":1,"WEDT":1,"WEST":1,"WET":1,"WST":1,"YAKT":1,"YEKT":1,"Z":1};
  717. return (timezones[value] === 1);
  718. };
  719. $D.validateTimezoneOffset= function(value) {
  720. // timezones go from +14hrs to -12hrs, the +X hours are negative offsets.
  721. return (value > -841 && value < 721);
  722. };
  723. }());
  724. (function () {
  725. var $D = Date,
  726. $P = $D.prototype,
  727. p = function (s, l) {
  728. if (!l) {
  729. l = 2;
  730. }
  731. return ("000" + s).slice(l * -1);
  732. };
  733. var validateConfigObject = function (obj) {
  734. var result = {}, self = this, prop, testFunc;
  735. testFunc = function (prop, func, value) {
  736. if (prop === "day") {
  737. var month = (obj.month !== undefined) ? obj.month : self.getMonth();
  738. var year = (obj.year !== undefined) ? obj.year : self.getFullYear();
  739. return $D[func](value, year, month);
  740. } else {
  741. return $D[func](value);
  742. }
  743. };
  744. for (prop in obj) {
  745. if (hasOwnProperty.call(obj, prop)) {
  746. var func = "validate" + prop.charAt(0).toUpperCase() + prop.slice(1);
  747. if ($D[func] && obj[prop] !== null && testFunc(prop, func, obj[prop])) {
  748. result[prop] = obj[prop];
  749. }
  750. }
  751. }
  752. return result;
  753. };
  754. /**
  755. * Resets the time of this Date object to 12:00 AM (00:00), which is the start of the day.
  756. * @param {Boolean} .clone() this date instance before clearing Time
  757. * @return {Date} this
  758. */
  759. $P.clearTime = function () {
  760. this.setHours(0);
  761. this.setMinutes(0);
  762. this.setSeconds(0);
  763. this.setMilliseconds(0);
  764. return this;
  765. };
  766. /**
  767. * Resets the time of this Date object to the current time ('now').
  768. * @return {Date} this
  769. */
  770. $P.setTimeToNow = function () {
  771. var n = new Date();
  772. this.setHours(n.getHours());
  773. this.setMinutes(n.getMinutes());
  774. this.setSeconds(n.getSeconds());
  775. this.setMilliseconds(n.getMilliseconds());
  776. return this;
  777. };
  778. /**
  779. * Returns a new Date object that is an exact date and time copy of the original instance.
  780. * @return {Date} A new Date instance
  781. */
  782. $P.clone = function () {
  783. return new Date(this.getTime());
  784. };
  785. /**
  786. * Compares this instance to a Date object and returns an number indication of their relative values.
  787. * @param {Date} Date object to compare [Required]
  788. * @return {Number} -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date.
  789. */
  790. $P.compareTo = function (date) {
  791. return Date.compare(this, date);
  792. };
  793. /**
  794. * Compares this instance to another Date object and returns true if they are equal.
  795. * @param {Date} Date object to compare. If no date to compare, new Date() [now] is used.
  796. * @return {Boolean} true if dates are equal. false if they are not equal.
  797. */
  798. $P.equals = function (date) {
  799. return Date.equals(this, (date !== undefined ? date : new Date()));
  800. };
  801. /**
  802. * Determines if this instance is between a range of two dates or equal to either the start or end dates.
  803. * @param {Date} Start of range [Required]
  804. * @param {Date} End of range [Required]
  805. * @return {Boolean} true is this is between or equal to the start and end dates, else false
  806. */
  807. $P.between = function (start, end) {
  808. return this.getTime() >= start.getTime() && this.getTime() <= end.getTime();
  809. };
  810. /**
  811. * Determines if this date occurs after the date to compare to.
  812. * @param {Date} Date object to compare. If no date to compare, new Date() ("now") is used.
  813. * @return {Boolean} true if this date instance is greater than the date to compare to (or "now"), otherwise false.
  814. */
  815. $P.isAfter = function (date) {
  816. return this.compareTo(date || new Date()) === 1;
  817. };
  818. /**
  819. * Determines if this date occurs before the date to compare to.
  820. * @param {Date} Date object to compare. If no date to compare, new Date() ("now") is used.
  821. * @return {Boolean} true if this date instance is less than the date to compare to (or "now").
  822. */
  823. $P.isBefore = function (date) {
  824. return (this.compareTo(date || new Date()) === -1);
  825. };
  826. /**
  827. * Determines if the current Date instance occurs today.
  828. * @return {Boolean} true if this date instance is 'today', otherwise false.
  829. */
  830. /**
  831. * Determines if the current Date instance occurs on the same Date as the supplied 'date'.
  832. * If no 'date' to compare to is provided, the current Date instance is compared to 'today'.
  833. * @param {date} Date object to compare. If no date to compare, the current Date ("now") is used.
  834. * @return {Boolean} true if this Date instance occurs on the same Day as the supplied 'date'.
  835. */
  836. $P.isToday = $P.isSameDay = function (date) {
  837. return this.clone().clearTime().equals((date || new Date()).clone().clearTime());
  838. };
  839. /**
  840. * Adds the specified number of milliseconds to this instance.
  841. * @param {Number} The number of milliseconds to add. The number can be positive or negative [Required]
  842. * @return {Date} this
  843. */
  844. $P.addMilliseconds = function (value) {
  845. if (!value) { return this; }
  846. this.setTime(this.getTime() + value * 1);
  847. return this;
  848. };
  849. /**
  850. * Adds the specified number of seconds to this instance.
  851. * @param {Number} The number of seconds to add. The number can be positive or negative [Required]
  852. * @return {Date} this
  853. */
  854. $P.addSeconds = function (value) {
  855. if (!value) { return this; }
  856. return this.addMilliseconds(value * 1000);
  857. };
  858. /**
  859. * Adds the specified number of seconds to this instance.
  860. * @param {Number} The number of seconds to add. The number can be positive or negative [Required]
  861. * @return {Date} this
  862. */
  863. $P.addMinutes = function (value) {
  864. if (!value) { return this; }
  865. return this.addMilliseconds(value * 60000); // 60*1000
  866. };
  867. /**
  868. * Adds the specified number of hours to this instance.
  869. * @param {Number} The number of hours to add. The number can be positive or negative [Required]
  870. * @return {Date} this
  871. */
  872. $P.addHours = function (value) {
  873. if (!value) { return this; }
  874. return this.addMilliseconds(value * 3600000); // 60*60*1000
  875. };
  876. /**
  877. * Adds the specified number of days to this instance.
  878. * @param {Number} The number of days to add. The number can be positive or negative [Required]
  879. * @return {Date} this
  880. */
  881. $P.addDays = function (value) {
  882. if (!value) { return this; }
  883. this.setDate(this.getDate() + value * 1);
  884. return this;
  885. };
  886. /**
  887. * Adds the specified number of weekdays (ie - not sat or sun) to this instance.
  888. * @param {Number} The number of days to add. The number can be positive or negative [Required]
  889. * @return {Date} this
  890. */
  891. $P.addWeekdays = function (value) {
  892. if (!value) { return this; }
  893. var day = this.getDay();
  894. var weeks = (Math.ceil(Math.abs(value)/7));
  895. if (day === 0 || day === 6) {
  896. if (value > 0) {
  897. this.next().monday();
  898. this.addDays(-1);
  899. day = this.getDay();
  900. }
  901. }
  902. if (value < 0) {
  903. while (value < 0) {
  904. this.addDays(-1);
  905. day = this.getDay();
  906. if (day !== 0 && day !== 6) {
  907. value++;
  908. }
  909. }
  910. return this;
  911. } else if (value > 5 || (6-day) <= value) {
  912. value = value + (weeks * 2);
  913. }
  914. return this.addDays(value);
  915. };
  916. /**
  917. * Adds the specified number of weeks to this instance.
  918. * @param {Number} The number of weeks to add. The number can be positive or negative [Required]
  919. * @return {Date} this
  920. */
  921. $P.addWeeks = function (value) {
  922. if (!value) { return this; }
  923. return this.addDays(value * 7);
  924. };
  925. /**
  926. * Adds the specified number of months to this instance.
  927. * @param {Number} The number of months to add. The number can be positive or negative [Required]
  928. * @return {Date} this
  929. */
  930. $P.addMonths = function (value) {
  931. if (!value) { return this; }
  932. var n = this.getDate();
  933. this.setDate(1);
  934. this.setMonth(this.getMonth() + value * 1);
  935. this.setDate(Math.min(n, $D.getDaysInMonth(this.getFullYear(), this.getMonth())));
  936. return this;
  937. };
  938. $P.addQuarters = function (value) {
  939. if (!value) { return this; }
  940. // note this will take you to the same point in the quarter as you are now.
  941. // i.e. - if you are 15 days into the quarter you'll be 15 days into the resulting one.
  942. // bonus: this allows adding fractional quarters
  943. return this.addMonths(value * 3);
  944. };
  945. /**
  946. * Adds the specified number of years to this instance.
  947. * @param {Number} The number of years to add. The number can be positive or negative [Required]
  948. * @return {Date} this
  949. */
  950. $P.addYears = function (value) {
  951. if (!value) { return this; }
  952. return this.addMonths(value * 12);
  953. };
  954. /**
  955. * Adds (or subtracts) to the value of the years, months, weeks, days, hours, minutes, seconds, milliseconds of the date instance using given configuration object. Positive and Negative values allowed.
  956. * Example
  957. <pre><code>
  958. Date.today().add( { days: 1, months: 1 } )
  959. new Date().add( { years: -1 } )
  960. </code></pre>
  961. * @param {Object} Configuration object containing attributes (months, days, etc.)
  962. * @return {Date} this
  963. */
  964. $P.add = function (config) {
  965. if (typeof config === "number") {
  966. this._orient = config;
  967. return this;
  968. }
  969. var x = config;
  970. if (x.day) {
  971. // If we should be a different date than today (eg: for 'tomorrow -1d', etc).
  972. // Should only effect parsing, not direct usage (eg, Finish and FinishExact)
  973. if ((x.day - this.getDate()) !== 0) {
  974. this.setDate(x.day);
  975. }
  976. }
  977. if (x.milliseconds) {
  978. this.addMilliseconds(x.milliseconds);
  979. }
  980. if (x.seconds) {
  981. this.addSeconds(x.seconds);
  982. }
  983. if (x.minutes) {
  984. this.addMinutes(x.minutes);
  985. }
  986. if (x.hours) {
  987. this.addHours(x.hours);
  988. }
  989. if (x.weeks) {
  990. this.addWeeks(x.weeks);
  991. }
  992. if (x.months) {
  993. this.addMonths(x.months);
  994. }
  995. if (x.years) {
  996. this.addYears(x.years);
  997. }
  998. if (x.days) {
  999. this.addDays(x.days);
  1000. }
  1001. return this;
  1002. };
  1003. /**
  1004. * Get the week number. Week one (1) is the week which contains the first Thursday of the year. Monday is considered the first day of the week.
  1005. * The .getWeek() function does NOT convert the date to UTC. The local datetime is used.
  1006. * Please use .getISOWeek() to get the week of the UTC converted date.
  1007. * @return {Number} 1 to 53
  1008. */
  1009. $P.getWeek = function (utc) {
  1010. // Create a copy of this date object
  1011. var self, target = new Date(this.valueOf());
  1012. if (utc) {
  1013. target.addMinutes(target.getTimezoneOffset());
  1014. self = target.clone();
  1015. } else {
  1016. self = this;
  1017. }
  1018. // ISO week date weeks start on monday
  1019. // so correct the day number
  1020. var dayNr = (self.getDay() + 6) % 7;
  1021. // ISO 8601 states that week 1 is the week
  1022. // with the first thursday of that year.
  1023. // Set the target date to the thursday in the target week
  1024. target.setDate(target.getDate() - dayNr + 3);
  1025. // Store the millisecond value of the target date
  1026. var firstThursday = target.valueOf();
  1027. // Set the target to the first thursday of the year
  1028. // First set the target to january first
  1029. target.setMonth(0, 1);
  1030. // Not a thursday? Correct the date to the next thursday
  1031. if (target.getDay() !== 4) {
  1032. target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
  1033. }
  1034. // The weeknumber is the number of weeks between the
  1035. // first thursday of the year and the thursday in the target week
  1036. return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000
  1037. };
  1038. /**
  1039. * Get the ISO 8601 week number. Week one ("01") is the week which contains the first Thursday of the year. Monday is considered the first day of the week.
  1040. * The .getISOWeek() function does convert the date to it's UTC value. Please use .getWeek() to get the week of the local date.
  1041. * @return {String} "01" to "53"
  1042. */
  1043. $P.getISOWeek = function () {
  1044. return p(this.getWeek(true));
  1045. };
  1046. /**
  1047. * Moves the date to Monday of the week set. Week one (1) is the week which contains the first Thursday of the year.
  1048. * @param {Number} A Number (1 to 53) that represents the week of the year.
  1049. * @return {Date} this
  1050. */
  1051. $P.setWeek = function (n) {
  1052. if ((n - this.getWeek()) === 0) {
  1053. if (this.getDay() !== 1) {
  1054. return this.moveToDayOfWeek(1, (this.getDay() > 1 ? -1 : 1));
  1055. } else {
  1056. return this;
  1057. }
  1058. } else {
  1059. return this.moveToDayOfWeek(1, (this.getDay() > 1 ? -1 : 1)).addWeeks(n - this.getWeek());
  1060. }
  1061. };
  1062. $P.setQuarter = function (qtr) {
  1063. var month = Math.abs(((qtr-1) * 3) + 1);
  1064. return this.setMonth(month, 1);
  1065. };
  1066. $P.getQuarter = function () {
  1067. return Date.getQuarter(this);
  1068. };
  1069. $P.getDaysLeftInQuarter = function () {
  1070. return Date.getDaysLeftInQuarter(this);
  1071. };
  1072. /**
  1073. * Moves the date to the next n'th occurrence of the dayOfWeek starting from the beginning of the month. The number (-1) is a magic number and will return the last occurrence of the dayOfWeek in the month.
  1074. * @param {Number} The dayOfWeek to move to
  1075. * @param {Number} The n'th occurrence to move to. Use (-1) to return the last occurrence in the month
  1076. * @return {Date} this
  1077. */
  1078. $P.moveToNthOccurrence = function (dayOfWeek, occurrence) {
  1079. if (dayOfWeek === "Weekday") {
  1080. if (occurrence > 0) {
  1081. this.moveToFirstDayOfMonth();
  1082. if (this.is().weekday()) {
  1083. occurrence -= 1;
  1084. }
  1085. } else if (occurrence < 0) {
  1086. this.moveToLastDayOfMonth();
  1087. if (this.is().weekday()) {
  1088. occurrence += 1;
  1089. }
  1090. } else {
  1091. return this;
  1092. }
  1093. return this.addWeekdays(occurrence);
  1094. }
  1095. var shift = 0;
  1096. if (occurrence > 0) {
  1097. shift = occurrence - 1;
  1098. }
  1099. else if (occurrence === -1) {
  1100. this.moveToLastDayOfMonth();
  1101. if (this.getDay() !== dayOfWeek) {
  1102. this.moveToDayOfWeek(dayOfWeek, -1);
  1103. }
  1104. return this;
  1105. }
  1106. return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek, +1).addWeeks(shift);
  1107. };
  1108. var moveToN = function (getFunc, addFunc, nVal) {
  1109. return function (value, orient) {
  1110. var diff = (value - this[getFunc]() + nVal * (orient || +1)) % nVal;
  1111. return this[addFunc]((diff === 0) ? diff += nVal * (orient || +1) : diff);
  1112. };
  1113. };
  1114. /**
  1115. * Move to the next or last dayOfWeek based on the orient value.
  1116. * @param {Number} The dayOfWeek to move to
  1117. * @param {Number} Forward (+1) or Back (-1). Defaults to +1. [Optional]
  1118. * @return {Date} this
  1119. */
  1120. $P.moveToDayOfWeek = moveToN("getDay", "addDays", 7);
  1121. /**
  1122. * Move to the next or last month based on the orient value.
  1123. * @param {Number} The month to move to. 0 = January, 11 = December
  1124. * @param {Number} Forward (+1) or Back (-1). Defaults to +1. [Optional]
  1125. * @return {Date} this
  1126. */
  1127. $P.moveToMonth = moveToN("getMonth", "addMonths", 12);
  1128. /**
  1129. * Get the Ordinate of the current day ("th", "st", "rd").
  1130. * @return {String}
  1131. */
  1132. $P.getOrdinate = function () {
  1133. var num = this.getDate();
  1134. return ord(num);
  1135. };
  1136. /**
  1137. * Get the Ordinal day (numeric day number) of the year, adjusted for leap year.
  1138. * @return {Number} 1 through 365 (366 in leap years)
  1139. */
  1140. $P.getOrdinalNumber = function () {
  1141. return Math.ceil((this.clone().clearTime() - new Date(this.getFullYear(), 0, 1)) / 86400000) + 1;
  1142. };
  1143. /**
  1144. * Get the time zone abbreviation of the current date.
  1145. * @return {String} The abbreviated time zone name (e.g. "EST")
  1146. */
  1147. $P.getTimezone = function () {
  1148. return $D.getTimezoneAbbreviation(this.getUTCOffset(), this.isDaylightSavingTime());
  1149. };
  1150. $P.setTimezoneOffset = function (offset) {
  1151. var here = this.getTimezoneOffset(), there = Number(offset) * -6 / 10;
  1152. return (there || there === 0) ? this.addMinutes(there - here) : this;
  1153. };
  1154. $P.setTimezone = function (offset) {
  1155. return this.setTimezoneOffset($D.getTimezoneOffset(offset));
  1156. };
  1157. /**
  1158. * Indicates whether Daylight Saving Time is observed in the current time zone.
  1159. * @return {Boolean} true|false
  1160. */
  1161. $P.hasDaylightSavingTime = function () {
  1162. return (Date.today().set({month: 0, day: 1}).getTimezoneOffset() !== Date.today().set({month: 6, day: 1}).getTimezoneOffset());
  1163. };
  1164. /**
  1165. * Indicates whether this Date instance is within the Daylight Saving Time range for the current time zone.
  1166. * @return {Boolean} true|false
  1167. */
  1168. $P.isDaylightSavingTime = function () {
  1169. return Date.today().set({month: 0, day: 1}).getTimezoneOffset() !== this.getTimezoneOffset();
  1170. };
  1171. /**
  1172. * Get the offset from UTC of the current date.
  1173. * @return {String} The 4-character offset string prefixed with + or - (e.g. "-0500")
  1174. */
  1175. $P.getUTCOffset = function (offset) {
  1176. var n = (offset || this.getTimezoneOffset()) * -10 / 6, r;
  1177. if (n < 0) {
  1178. r = (n - 10000).toString();
  1179. return r.charAt(0) + r.substr(2);
  1180. } else {
  1181. r = (n + 10000).toString();
  1182. return "+" + r.substr(1);
  1183. }
  1184. };
  1185. /**
  1186. * Returns the number of milliseconds between this date and date.
  1187. * @param {Date} Defaults to now
  1188. * @return {Number} The diff in milliseconds
  1189. */
  1190. $P.getElapsed = function (date) {
  1191. return (date || new Date()) - this;
  1192. };
  1193. /**
  1194. * Set the value of year, month, day, hour, minute, second, millisecond of date instance using given configuration object.
  1195. * Example
  1196. <pre><code>
  1197. Date.today().set( { day: 20, month: 1 } )
  1198. new Date().set( { millisecond: 0 } )
  1199. </code></pre>
  1200. *
  1201. * @param {Object} Configuration object containing attributes (month, day, etc.)
  1202. * @return {Date} this
  1203. */
  1204. $P.set = function (config) {
  1205. config = validateConfigObject.call(this, config);
  1206. var key;
  1207. for (key in config) {
  1208. if (hasOwnProperty.call(config, key)) {
  1209. var name = key.charAt(0).toUpperCase() + key.slice(1);
  1210. var addFunc, getFunc;
  1211. if (key !== "week" && key !== "month" && key !== "timezone" && key !== "timezoneOffset") {
  1212. name += "s";
  1213. }
  1214. addFunc = "add" + name;
  1215. getFunc = "get" + name;
  1216. if (key === "month") {
  1217. addFunc = addFunc + "s";
  1218. } else if (key === "year"){
  1219. getFunc = "getFullYear";
  1220. }
  1221. if (key !== "day" && key !== "timezone" && key !== "timezoneOffset" && key !== "week" && key !== "hour") {
  1222. this[addFunc](config[key] - this[getFunc]());
  1223. } else if ( key === "timezone"|| key === "timezoneOffset" || key === "week" || key === "hour") {
  1224. this["set"+name](config[key]);
  1225. }
  1226. }
  1227. }
  1228. // day has to go last because you can't validate the day without first knowing the month
  1229. if (config.day) {
  1230. this.addDays(config.day - this.getDate());
  1231. }
  1232. return this;
  1233. };
  1234. /**
  1235. * Moves the date to the first day of the month.
  1236. * @return {Date} this
  1237. */
  1238. $P.moveToFirstDayOfMonth = function () {
  1239. return this.set({ day: 1 });
  1240. };
  1241. /**
  1242. * Moves the date to the last day of the month.
  1243. * @return {Date} this
  1244. */
  1245. $P.moveToLastDayOfMonth = function () {
  1246. return this.set({ day: $D.getDaysInMonth(this.getFullYear(), this.getMonth())});
  1247. };
  1248. /**
  1249. * Converts the value of the current Date object to its equivalent string representation.
  1250. * Format Specifiers
  1251. * CUSTOM DATE AND TIME FORMAT STRINGS
  1252. * Format Description Example
  1253. * ------ --------------------------------------------------------------------------- -----------------------
  1254. * s The seconds of the minute between 0-59. "0" to "59"
  1255. * ss The seconds of the minute with leading zero if required. "00" to "59"
  1256. *
  1257. * m The minute of the hour between 0-59. "0" or "59"
  1258. * mm The minute of the hour with leading zero if required. "00" or "59"
  1259. *
  1260. * h The hour of the day between 1-12. "1" to "12"
  1261. * hh The hour of the day with leading zero if required. "01" to "12"
  1262. *
  1263. * H The hour of the day between 0-23. "0" to "23"
  1264. * HH The hour of the day with leading zero if required. "00" to "23"
  1265. *
  1266. * d The day of the month between 1 and 31. "1" to "31"
  1267. * dd The day of the month with leading zero if required. "01" to "31"
  1268. * ddd Abbreviated day name. Date.CultureInfo.abbreviatedDayNames. "Mon" to "Sun"
  1269. * dddd The full day name. Date.CultureInfo.dayNames. "Monday" to "Sunday"
  1270. *
  1271. * M The month of the year between 1-12. "1" to "12"
  1272. * MM The month of the year with leading zero if required. "01" to "12"
  1273. * MMM Abbreviated month name. Date.CultureInfo.abbreviatedMonthNames. "Jan" to "Dec"
  1274. * MMMM The full month name. Date.CultureInfo.monthNames. "January" to "December"
  1275. *
  1276. * yy The year as a two-digit number. "99" or "08"
  1277. * yyyy The full four digit year. "1999" or "2008"
  1278. *
  1279. * t Displays the first character of the A.M./P.M. designator. "A" or "P"
  1280. * Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator
  1281. * tt Displays the A.M./P.M. designator. "AM" or "PM"
  1282. * Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator
  1283. *
  1284. * S The ordinal suffix ("st, "nd", "rd" or "th") of the current day. "st, "nd", "rd" or "th"
  1285. *
  1286. * STANDARD DATE AND TIME FORMAT STRINGS
  1287. * Format Description Example
  1288. *------ --------------------------------------------------------------------------- -----------------------
  1289. * d The CultureInfo shortDate Format Pattern "M/d/yyyy"
  1290. * D The CultureInfo longDate Format Pattern "dddd, MMMM dd, yyyy"
  1291. * F The CultureInfo fullDateTime Format Pattern "dddd, MMMM dd, yyyy h:mm:ss tt"
  1292. * m The CultureInfo monthDay Format Pattern "MMMM dd"
  1293. * r The CultureInfo rfc1123 Format Pattern "ddd, dd MMM yyyy HH:mm:ss GMT"
  1294. * s The CultureInfo sortableDateTime Format Pattern "yyyy-MM-ddTHH:mm:ss"
  1295. * t The CultureInfo shortTime Format Pattern "h:mm tt"
  1296. * T The CultureInfo longTime Format Pattern "h:mm:ss tt"
  1297. * u The CultureInfo universalSortableDateTime Format Pattern "yyyy-MM-dd HH:mm:ssZ"
  1298. * y The CultureInfo yearMonth Format Pattern "MMMM, yyyy"
  1299. *
  1300. * @param {String} A format string consisting of one or more format spcifiers [Optional].
  1301. * @return {String} A string representation of the current Date object.
  1302. */
  1303. var ord = function (n) {
  1304. switch (n * 1) {
  1305. case 1:
  1306. case 21:
  1307. case 31:
  1308. return "st";
  1309. case 2:
  1310. case 22:
  1311. return "nd";
  1312. case 3:
  1313. case 23:
  1314. return "rd";
  1315. default:
  1316. return "th";
  1317. }
  1318. };
  1319. var parseStandardFormats = function (format) {
  1320. var y, c = Date.CultureInfo.formatPatterns;
  1321. switch (format) {
  1322. case "d":
  1323. return this.toString(c.shortDate);
  1324. case "D":
  1325. return this.toString(c.longDate);
  1326. case "F":
  1327. return this.toString(c.fullDateTime);
  1328. case "m":
  1329. return this.toString(c.monthDay);
  1330. case "r":
  1331. case "R":
  1332. y = this.clone().addMinutes(this.getTimezoneOffset());
  1333. return y.toString(c.rfc1123) + " GMT";
  1334. case "s":
  1335. return this.toString(c.sortableDateTime);
  1336. case "t":
  1337. return this.toString(c.shortTime);
  1338. case "T":
  1339. return this.toString(c.longTime);
  1340. case "u":
  1341. y = this.clone().addMinutes(this.getTimezoneOffset());
  1342. return y.toString(c.universalSortableDateTime);
  1343. case "y":
  1344. return this.toString(c.yearMonth);
  1345. default:
  1346. return false;
  1347. }
  1348. };
  1349. var parseFormatStringsClosure = function (context) {
  1350. return function (m) {
  1351. if (m.charAt(0) === "\\") {
  1352. return m.replace("\\", "");
  1353. }
  1354. switch (m) {
  1355. case "hh":
  1356. return p(context.getHours() < 13 ? (context.getHours() === 0 ? 12 : context.getHours()) : (context.getHours() - 12));
  1357. case "h":
  1358. return context.getHours() < 13 ? (context.getHours() === 0 ? 12 : context.getHours()) : (context.getHours() - 12);
  1359. case "HH":
  1360. return p(context.getHours());
  1361. case "H":
  1362. return context.getHours();
  1363. case "mm":
  1364. return p(context.getMinutes());
  1365. case "m":
  1366. return context.getMinutes();
  1367. case "ss":
  1368. return p(context.getSeconds());
  1369. case "s":
  1370. return context.getSeconds();
  1371. case "yyyy":
  1372. return p(context.getFullYear(), 4);
  1373. case "yy":
  1374. return p(context.getFullYear());
  1375. case "y":
  1376. return context.getFullYear();
  1377. case "E":
  1378. case "dddd":
  1379. return Date.CultureInfo.dayNames[context.getDay()];
  1380. case "ddd":
  1381. return Date.CultureInfo.abbreviatedDayNames[context.getDay()];
  1382. case "dd":
  1383. return p(context.getDate());
  1384. case "d":
  1385. return context.getDate();
  1386. case "MMMM":
  1387. return Date.CultureInfo.monthNames[context.getMonth()];
  1388. case "MMM":
  1389. return Date.CultureInfo.abbreviatedMonthNames[context.getMonth()];
  1390. case "MM":
  1391. return p((context.getMonth() + 1));
  1392. case "M":
  1393. return context.getMonth() + 1;
  1394. case "t":
  1395. return context.getHours() < 12 ? Date.CultureInfo.amDesignator.substring(0, 1) : Date.CultureInfo.pmDesignator.substring(0, 1);
  1396. case "tt":
  1397. return context.getHours() < 12 ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator;
  1398. case "S":
  1399. return ord(context.getDate());
  1400. case "W":
  1401. return context.getWeek();
  1402. case "WW":
  1403. return context.getISOWeek();
  1404. case "Q":
  1405. return "Q" + context.getQuarter();
  1406. case "q":
  1407. return String(context.getQuarter());
  1408. case "z":
  1409. return context.getTimezone();
  1410. case "Z":
  1411. case "X":
  1412. return Date.getTimezoneOffset(context.getTimezone());
  1413. case "ZZ": // Timezone offset in seconds
  1414. return context.getTimezoneOffset() * -60;
  1415. case "u":
  1416. return context.getDay();
  1417. case "L":
  1418. return ($D.isLeapYear(context.getFullYear())) ? 1 : 0;
  1419. case "B":
  1420. // Swatch Internet Time (.beats)
  1421. return "@"+((context.getUTCSeconds() + (context.getUTCMinutes()*60) + ((context.getUTCHours()+1)*3600))/86.4);
  1422. default:
  1423. return m;
  1424. }
  1425. };
  1426. };
  1427. $P.toString = function (format, ignoreStandards) {
  1428. // Standard Date and Time Format Strings. Formats pulled from CultureInfo file and
  1429. // may vary by culture.
  1430. if (!ignoreStandards && format && format.length === 1) {
  1431. output = parseStandardFormats.call(this, format);
  1432. if (output) {
  1433. return output;
  1434. }
  1435. }
  1436. var parseFormatStrings = parseFormatStringsClosure(this);
  1437. return format ? format.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g, parseFormatStrings).replace(/\[|\]/g, "") : this._toString();
  1438. };
  1439. }());
  1440. /*************************************************************
  1441. * SugarPak - Domain Specific Language - Syntactical Sugar *
  1442. *************************************************************/
  1443. (function () {
  1444. var $D = Date, $P = $D.prototype, $N = Number.prototype;
  1445. // private
  1446. $P._orient = +1;
  1447. // private
  1448. $P._nth = null;
  1449. // private
  1450. $P._is = false;
  1451. // private
  1452. $P._same = false;
  1453. // private
  1454. $P._isSecond = false;
  1455. // private
  1456. $N._dateElement = "days";
  1457. /**
  1458. * Moves the date to the next instance of a date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()).
  1459. * Example
  1460. <pre><code>
  1461. Date.today().next().friday();
  1462. Date.today().next().fri();
  1463. Date.today().next().march();
  1464. Date.today().next().mar();
  1465. Date.today().next().week();
  1466. </code></pre>
  1467. *
  1468. * @return {Date} date
  1469. */
  1470. $P.next = function () {
  1471. this._move = true;
  1472. this._orient = +1;
  1473. return this;
  1474. };
  1475. /**
  1476. * Creates a new Date (Date.today()) and moves the date to the next instance of the date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()).
  1477. * Example
  1478. <pre><code>
  1479. Date.next().friday();
  1480. Date.next().fri();
  1481. Date.next().march();
  1482. Date.next().mar();
  1483. Date.next().week();
  1484. </code></pre>
  1485. *
  1486. * @return {Date} date
  1487. */
  1488. $D.next = function () {
  1489. return $D.today().next();
  1490. };
  1491. /**
  1492. * Moves the date to the previous instance of a date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()).
  1493. * Example
  1494. <pre><code>
  1495. Date.today().last().friday();
  1496. Date.today().last().fri();
  1497. Date.today().last().march();
  1498. Date.today().last().mar();
  1499. Date.today().last().week();
  1500. </code></pre>
  1501. *
  1502. * @return {Date} date
  1503. */
  1504. $P.last = $P.prev = $P.previous = function () {
  1505. this._move = true;
  1506. this._orient = -1;
  1507. return this;
  1508. };
  1509. /**
  1510. * Creates a new Date (Date.today()) and moves the date to the previous instance of the date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()).
  1511. * Example
  1512. <pre><code>
  1513. Date.last().friday();
  1514. Date.last().fri();
  1515. Date.previous().march();
  1516. Date.prev().mar();
  1517. Date.last().week();
  1518. </code></pre>
  1519. *
  1520. * @return {Date} date
  1521. */
  1522. $D.last = $D.prev = $D.previous = function () {
  1523. return $D.today().last();
  1524. };
  1525. /**
  1526. * Performs a equality check when followed by either a month name, day name or .weekday() function.
  1527. * Example
  1528. <pre><code>
  1529. Date.today().is().friday(); // true|false
  1530. Date.today().is().fri();
  1531. Date.today().is().march();
  1532. Date.today().is().mar();
  1533. </code></pre>
  1534. *
  1535. * @return {Boolean} true|false
  1536. */
  1537. $P.is = function () {
  1538. this._is = true;
  1539. return this;
  1540. };
  1541. /**
  1542. * Determines if two date objects occur on/in exactly the same instance of the subsequent date part function.
  1543. * The function .same() must be followed by a date part function (example: .day(), .month(), .year(), etc).
  1544. *
  1545. * An optional Date can be passed in the date part function. If now date is passed as a parameter, 'Now' is used.
  1546. *
  1547. * The following example demonstrates how to determine if two dates fall on the exact same day.
  1548. *
  1549. * Example
  1550. <pre><code>
  1551. var d1 = Date.today(); // today at 00:00
  1552. var d2 = new Date(); // exactly now.
  1553. // Do they occur on the same day?
  1554. d1.same().day(d2); // true
  1555. // Do they occur on the same hour?
  1556. d1.same().hour(d2); // false, unless d2 hour is '00' (midnight).
  1557. // What if it's the same day, but one year apart?
  1558. var nextYear = Date.today().add(1).year();
  1559. d1.same().day(nextYear); // false, because the dates must occur on the exact same day.
  1560. </code></pre>
  1561. *
  1562. * Scenario: Determine if a given date occurs during some week period 2 months from now.
  1563. *
  1564. * Example
  1565. <pre><code>
  1566. var future = Date.today().add(2).months();
  1567. return someDate.same().week(future); // true|false;
  1568. </code></pre>
  1569. *
  1570. * @return {Boolean} true|false
  1571. */
  1572. $P.same = function () {
  1573. this._same = true;
  1574. this._isSecond = false;
  1575. return this;
  1576. };
  1577. /**
  1578. * Determines if the current date/time occurs during Today. Must be preceded by the .is() function.
  1579. * Example
  1580. <pre><code>
  1581. someDate.is().today(); // true|false
  1582. new Date().is().today(); // true
  1583. Date.today().is().today();// true
  1584. Date.today().add(-1).day().is().today(); // false
  1585. </code></pre>
  1586. *
  1587. * @return {Boolean} true|false
  1588. */
  1589. $P.today = function () {
  1590. return this.same().day();
  1591. };
  1592. /**
  1593. * Determines if the current date is a weekday. This function must be preceded by the .is() function.
  1594. * Example
  1595. <pre><code>
  1596. Date.today().is().weekday(); // true|false
  1597. </code></pre>
  1598. *
  1599. * @return {Boolean} true|false
  1600. */
  1601. $P.weekday = function () {
  1602. if (this._nth) {
  1603. return df("Weekday").call(this);
  1604. }
  1605. if (this._move) {
  1606. return this.addWeekdays(this._orient);
  1607. }
  1608. if (this._is) {
  1609. this._is = false;
  1610. return (!this.is().sat() && !this.is().sun());
  1611. }
  1612. return false;
  1613. };
  1614. /**
  1615. * Determines if the current date is on the weekend. This function must be preceded by the .is() function.
  1616. * Example
  1617. <pre><code>
  1618. Date.today().is().weekend(); // true|false
  1619. </code></pre>
  1620. *
  1621. * @return {Boolean} true|false
  1622. */
  1623. $P.weekend = function () {
  1624. if (this._is) {
  1625. this._is = false;
  1626. return (this.is().sat() || this.is().sun());
  1627. }
  1628. return false;
  1629. };
  1630. /**
  1631. * Sets the Time of the current Date instance. A string "6:15 pm" or config object {hour:18, minute:15} are accepted.
  1632. * Example
  1633. <pre><code>
  1634. // Set time to 6:15pm with a String
  1635. Date.today().at("6:15pm");
  1636. // Set time to 6:15pm with a config object
  1637. Date.today().at({hour:18, minute:15});
  1638. </code></pre>
  1639. *
  1640. * @return {Date} date
  1641. */
  1642. $P.at = function (time) {
  1643. return (typeof time === "string") ? $D.parse(this.toString("d") + " " + time) : this.set(time);
  1644. };
  1645. /**
  1646. * Creates a new Date() and adds this (Number) to the date based on the preceding date element function (eg. second|minute|hour|day|month|year).
  1647. * Example
  1648. <pre><code>
  1649. // Undeclared Numbers must be wrapped with parentheses. Requirment of JavaScript.
  1650. (3).days().fromNow();
  1651. (6).months().fromNow();
  1652. // Declared Number variables do not require parentheses.
  1653. var n = 6;
  1654. n.months().fromNow();
  1655. </code></pre>
  1656. *
  1657. * @return {Date} A new Date instance
  1658. */
  1659. $N.fromNow = $N.after = function (date) {
  1660. var c = {};
  1661. c[this._dateElement] = this;
  1662. return ((!date) ? new Date() : date.clone()).add(c);
  1663. };
  1664. /**
  1665. * Creates a new Date() and subtract this (Number) from the date based on the preceding date element function (eg. second|minute|hour|day|month|year).
  1666. * Example
  1667. <pre><code>
  1668. // Undeclared Numbers must be wrapped with parentheses. Requirment of JavaScript.
  1669. (3).days().ago();
  1670. (6).months().ago();
  1671. // Declared Number variables do not require parentheses.
  1672. var n = 6;
  1673. n.months().ago();
  1674. </code></pre>
  1675. *
  1676. * @return {Date} A new Date instance
  1677. */
  1678. $N.ago = $N.before = function (date) {
  1679. var c = {},
  1680. s = (this._dateElement[this._dateElement.length-1] !== "s") ? this._dateElement + "s" : this._dateElement;
  1681. c[s] = this * -1;
  1682. return ((!date) ? new Date() : date.clone()).add(c);
  1683. };
  1684. // Do NOT modify the following string tokens. These tokens are used to build dynamic functions.
  1685. // All culture-specific strings can be found in the CultureInfo files.
  1686. var dx = ("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),
  1687. mx = ("january february march april may june july august september october november december").split(/\s/),
  1688. px = ("Millisecond Second Minute Hour Day Week Month Year Quarter Weekday").split(/\s/),
  1689. pxf = ("Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter").split(/\s/),
  1690. nth = ("final first second third fourth fifth").split(/\s/),
  1691. de;
  1692. /**
  1693. * Returns an object literal of all the date parts.
  1694. * Example
  1695. <pre><code>
  1696. var o = new Date().toObject();
  1697. // { year: 2008, month: 4, week: 20, day: 13, hour: 18, minute: 9, second: 32, millisecond: 812 }
  1698. // The object properties can be referenced directly from the object.
  1699. alert(o.day); // alerts "13"
  1700. alert(o.year); // alerts "2008"
  1701. </code></pre>
  1702. *
  1703. * @return {Date} An object literal representing the original date object.
  1704. */
  1705. $P.toObject = function () {
  1706. var o = {};
  1707. for (var i = 0; i < px.length; i++) {
  1708. if (this["get" + pxf[i]]) {
  1709. o[px[i].toLowerCase()] = this["get" + pxf[i]]();
  1710. }
  1711. }
  1712. return o;
  1713. };
  1714. /**
  1715. * Returns a date created from an object literal. Ignores the .week property if set in the config.
  1716. * Example
  1717. <pre><code>
  1718. var o = new Date().toObject();
  1719. return Date.fromObject(o); // will return the same date.
  1720. var o2 = {month: 1, day: 20, hour: 18}; // birthday party!
  1721. Date.fromObject(o2);
  1722. </code></pre>
  1723. *
  1724. * @return {Date} An object literal representing the original date object.
  1725. */
  1726. $D.fromObject = function(config) {
  1727. config.week = null;
  1728. return Date.today().set(config);
  1729. };
  1730. // Create day name functions and abbreviated day name functions (eg. monday(), friday(), fri()).
  1731. var df = function (n) {
  1732. return function () {
  1733. if (this._is) {
  1734. this._is = false;
  1735. return this.getDay() === n;
  1736. }
  1737. if (this._move) { this._move = null; }
  1738. if (this._nth !== null) {
  1739. // If the .second() function was called earlier, remove the _orient
  1740. // from the date, and then continue.
  1741. // This is required because 'second' can be used in two different context.
  1742. //
  1743. // Example
  1744. //
  1745. // Date.today().add(1).second();
  1746. // Date.march().second().monday();
  1747. //
  1748. // Things get crazy with the following...
  1749. // Date.march().add(1).second().second().monday(); // but it works!!
  1750. //
  1751. if (this._isSecond) {
  1752. this.addSeconds(this._orient * -1);
  1753. }
  1754. // make sure we reset _isSecond
  1755. this._isSecond = false;
  1756. var ntemp = this._nth;
  1757. this._nth = null;
  1758. var temp = this.clone().moveToLastDayOfMonth();
  1759. this.moveToNthOccurrence(n, ntemp);
  1760. if (this > temp) {
  1761. throw new RangeError($D.getDayName(n) + " does not occur " + ntemp + " times in the month of " + $D.getMonthName(temp.getMonth()) + " " + temp.getFullYear() + ".");
  1762. }
  1763. return this;
  1764. }
  1765. return this.moveToDayOfWeek(n, this._orient);
  1766. };
  1767. };
  1768. var sdf = function (n) {
  1769. return function () {
  1770. var t = $D.today(), shift = n - t.getDay();
  1771. if (n === 0 && Date.CultureInfo.firstDayOfWeek === 1 && t.getDay() !== 0) {
  1772. shift = shift + 7;
  1773. }
  1774. return t.addDays(shift);
  1775. };
  1776. };
  1777. // Create month name functions and abbreviated month name functions (eg. january(), march(), mar()).
  1778. var month_instance_functions = function (n) {
  1779. return function () {
  1780. if (this._is) {
  1781. this._is = false;
  1782. return this.getMonth() === n;
  1783. }
  1784. return this.moveToMonth(n, this._orient);
  1785. };
  1786. };
  1787. var month_static_functions = function (n) {
  1788. return function () {
  1789. return $D.today().set({ month: n, day: 1 });
  1790. };
  1791. };
  1792. var processTerms = function (names, staticFunc, instanceFunc) {
  1793. for (var i = 0; i < names.length; i++) {
  1794. // Create constant static Name variables.
  1795. $D[names[i].toUpperCase()] = $D[names[i].toUpperCase().substring(0, 3)] = i;
  1796. // Create Name functions.
  1797. $D[names[i]] = $D[names[i].substring(0, 3)] = staticFunc(i);
  1798. // Create Name instance functions.
  1799. $P[names[i]] = $P[names[i].substring(0, 3)] = instanceFunc(i);
  1800. }
  1801. };
  1802. processTerms(dx, sdf, df);
  1803. processTerms(mx, month_static_functions, month_instance_functions);
  1804. // Create date element functions and plural date element functions used with Date (eg. day(), days(), months()).
  1805. var ef = function (j) {
  1806. return function () {
  1807. // if the .second() function was called earlier, the _orient
  1808. // has alread been added. Just return this and reset _isSecond.
  1809. if (this._isSecond) {
  1810. this._isSecond = false;
  1811. return this;
  1812. }
  1813. if (this._same) {
  1814. this._same = this._is = false;
  1815. var o1 = this.toObject(),
  1816. o2 = (arguments[0] || new Date()).toObject(),
  1817. v = "",
  1818. k = j.toLowerCase();
  1819. // the substr trick with -1 doesn't work in IE8 or less
  1820. k = (k[k.length-1] === "s") ? k.substring(0,k.length-1) : k;
  1821. for (var m = (px.length - 1); m > -1; m--) {
  1822. v = px[m].toLowerCase();
  1823. if (o1[v] !== o2[v]) {
  1824. return false;
  1825. }
  1826. if (k === v) {
  1827. break;
  1828. }
  1829. }
  1830. return true;
  1831. }
  1832. if (j.substring(j.length - 1) !== "s") {
  1833. j += "s";
  1834. }
  1835. if (this._move) { this._move = null; }
  1836. return this["add" + j](this._orient);
  1837. };
  1838. };
  1839. var nf = function (n) {
  1840. return function () {
  1841. this._dateElement = n;
  1842. return this;
  1843. };
  1844. };
  1845. for (var k = 0; k < px.length; k++) {
  1846. de = px[k].toLowerCase();
  1847. if(de !== "weekday") {
  1848. // Create date element functions and plural date element functions used with Date (eg. day(), days(), months()).
  1849. $P[de] = $P[de + "s"] = ef(px[k]);
  1850. // Create date element functions and plural date element functions used with Number (eg. day(), days(), months()).
  1851. $N[de] = $N[de + "s"] = nf(de + "s");
  1852. }
  1853. }
  1854. $P._ss = ef("Second");
  1855. var nthfn = function (n) {
  1856. return function (dayOfWeek) {
  1857. if (this._same) {
  1858. return this._ss(arguments[0]);
  1859. }
  1860. if (dayOfWeek || dayOfWeek === 0) {
  1861. return this.moveToNthOccurrence(dayOfWeek, n);
  1862. }
  1863. this._nth = n;
  1864. // if the operator is 'second' add the _orient, then deal with it later...
  1865. if (n === 2 && (dayOfWeek === undefined || dayOfWeek === null)) {
  1866. this._isSecond = true;
  1867. return this.addSeconds(this._orient);
  1868. }
  1869. return this;
  1870. };
  1871. };
  1872. for (var l = 0; l < nth.length; l++) {
  1873. $P[nth[l]] = (l === 0) ? nthfn(-1) : nthfn(l);
  1874. }
  1875. }());
  1876. (function () {
  1877. "use strict";
  1878. Date.Parsing = {
  1879. Exception: function (s) {
  1880. this.message = "Parse error at '" + s.substring(0, 10) + " ...'";
  1881. }
  1882. };
  1883. var $P = Date.Parsing;
  1884. var dayOffsets = {
  1885. standard: [0,31,59,90,120,151,181,212,243,273,304,334],
  1886. leap: [0,31,60,91,121,152,182,213,244,274,305,335]
  1887. };
  1888. $P.isLeapYear = function(year) {
  1889. return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
  1890. };
  1891. var utils = {
  1892. multiReplace : function (str, hash ) {
  1893. var key;
  1894. for (key in hash) {
  1895. if (Object.prototype.hasOwnProperty.call(hash, key)) {
  1896. var regex;
  1897. if (typeof hash[key] === "function") {
  1898. } else {
  1899. regex = (hash[key] instanceof RegExp) ? hash[key] : new RegExp(hash[key], "g");
  1900. }
  1901. str = str.replace(regex, key);
  1902. }
  1903. }
  1904. return str;
  1905. },
  1906. getDayOfYearFromWeek : function (obj) {
  1907. var d, jan4, offset;
  1908. obj.weekDay = (!obj.weekDay && obj.weekDay !== 0) ? 1 : obj.weekDay;
  1909. d = new Date(obj.year, 0, 4);
  1910. jan4 = d.getDay() === 0 ? 7 : d.getDay(); // JS is 0 indexed on Sunday.
  1911. offset = jan4+3;
  1912. obj.dayOfYear = ((obj.week * 7) + (obj.weekDay === 0 ? 7 : obj.weekDay))-offset;
  1913. return obj;
  1914. },
  1915. getDayOfYear : function (obj, dayOffset) {
  1916. if (!obj.dayOfYear) {
  1917. obj = utils.getDayOfYearFromWeek(obj);
  1918. }
  1919. for (var i=0;i <= dayOffset.length;i++) {
  1920. if (obj.dayOfYear < dayOffset[i] || i === dayOffset.length) {
  1921. obj.day = obj.day ? obj.day : (obj.dayOfYear - dayOffset[i-1]);
  1922. break;
  1923. } else {
  1924. obj.month = i;
  1925. }
  1926. }
  1927. return obj;
  1928. },
  1929. adjustForTimeZone : function (obj, date) {
  1930. var offset;
  1931. if (obj.zone.toUpperCase() === "Z" || (obj.zone_hours === 0 && obj.zone_minutes === 0)) {
  1932. // it's UTC/GML so work out the current timeszone offset
  1933. offset = -date.getTimezoneOffset();
  1934. } else {
  1935. offset = (obj.zone_hours*60) + (obj.zone_minutes || 0);
  1936. if (obj.zone_sign === "+") {
  1937. offset *= -1;
  1938. }
  1939. offset -= date.getTimezoneOffset();
  1940. }
  1941. date.setMinutes(date.getMinutes()+offset);
  1942. return date;
  1943. },
  1944. setDefaults : function (obj) {
  1945. obj.year = obj.year || Date.today().getFullYear();
  1946. obj.hours = obj.hours || 0;
  1947. obj.minutes = obj.minutes || 0;
  1948. obj.seconds = obj.seconds || 0;
  1949. obj.milliseconds = obj.milliseconds || 0;
  1950. if (!(!obj.month && (obj.week || obj.dayOfYear))) {
  1951. // if we have a month, or if we don't but don't have the day calculation data
  1952. obj.month = obj.month || 0;
  1953. obj.day = obj.day || 1;
  1954. }
  1955. return obj;
  1956. },
  1957. dataNum: function (data, mod, explict, postProcess) {
  1958. var dataNum = data*1;
  1959. if (mod) {
  1960. if (postProcess) {
  1961. return data ? mod(data)*1 : data;
  1962. } else {
  1963. return data ? mod(dataNum) : data;
  1964. }
  1965. } else if (!explict){
  1966. return data ? dataNum : data;
  1967. } else {
  1968. return (data && typeof data !== "undefined") ? dataNum : data;
  1969. }
  1970. },
  1971. timeDataProcess: function (obj) {
  1972. var timeObj = {};
  1973. for (var x in obj.data) {
  1974. if (obj.data.hasOwnProperty(x)) {
  1975. timeObj[x] = obj.ignore[x] ? obj.data[x] : utils.dataNum(obj.data[x], obj.mods[x], obj.explict[x], obj.postProcess[x]);
  1976. }
  1977. }
  1978. if (obj.data.secmins) {
  1979. obj.data.secmins = obj.data.secmins.replace(",", ".") * 60;
  1980. if (!timeObj.minutes) {
  1981. timeObj.minutes = obj.data.secmins;
  1982. } else if (!timeObj.seconds) {
  1983. timeObj.seconds = obj.data.secmins;
  1984. }
  1985. delete obj.secmins;
  1986. }
  1987. return timeObj;
  1988. },
  1989. buildTimeObjectFromData: function (data) {
  1990. var time = utils.timeDataProcess({
  1991. data: {
  1992. year : data[1],
  1993. month : data[5],
  1994. day : data[7],
  1995. week : data[8],
  1996. dayOfYear : data[10],
  1997. hours : data[15],
  1998. zone_hours : data[23],
  1999. zone_minutes : data[24],
  2000. zone : data[21],
  2001. zone_sign : data[22],
  2002. weekDay : data[9],
  2003. minutes: data[16],
  2004. seconds: data[19],
  2005. milliseconds: data[20],
  2006. secmins: data[18]
  2007. },
  2008. mods: {
  2009. month: function(data) {
  2010. return data-1;
  2011. },
  2012. weekDay: function (data) {
  2013. data = Math.abs(data);
  2014. return (data === 7 ? 0 : data);
  2015. },
  2016. minutes: function (data) {
  2017. return data.replace(":","");
  2018. },
  2019. seconds: function (data) {
  2020. return Math.floor( (data.replace(":","").replace(",","."))*1 );
  2021. },
  2022. milliseconds: function (data) {
  2023. return (data.replace(",",".")*1000);
  2024. }
  2025. },
  2026. postProcess: {
  2027. minutes: true,
  2028. seconds: true,
  2029. milliseconds: true
  2030. },
  2031. explict: {
  2032. zone_hours: true,
  2033. zone_minutes: true
  2034. },
  2035. ignore: {
  2036. zone: true,
  2037. zone_sign: true,
  2038. secmins: true
  2039. }
  2040. });
  2041. return time;
  2042. },
  2043. addToHash: function (hash, keys, data) {
  2044. keys = keys;
  2045. data = data;
  2046. var len = keys.length;
  2047. for (var i = 0; i < len; i++) {
  2048. hash[keys[i]] = data[i];
  2049. }
  2050. return hash;
  2051. },
  2052. combineRegex: function (r1, r2) {
  2053. return new RegExp("(("+r1.source+")\\s("+r2.source+"))");
  2054. },
  2055. getDateNthString: function(add, last, inc){
  2056. if (add) {
  2057. return Date.today().addDays(inc).toString("d");
  2058. } else if (last) {
  2059. return Date.today().last()[inc]().toString("d");
  2060. }
  2061. },
  2062. buildRegexData: function (array) {
  2063. var arr = [];
  2064. var len = array.length;
  2065. for (var i=0; i < len; i++) {
  2066. if (Object.prototype.toString.call(array[i]) === '[object Array]') { // oldIE compat version of Array.isArray
  2067. arr.push(this.combineRegex(array[i][0], array[i][1]));
  2068. } else {
  2069. arr.push(array[i]);
  2070. }
  2071. }
  2072. return arr;
  2073. }
  2074. };
  2075. $P.processTimeObject = function (obj) {
  2076. var date, dayOffset;
  2077. utils.setDefaults(obj);
  2078. dayOffset = ($P.isLeapYear(obj.year)) ? dayOffsets.leap : dayOffsets.standard;
  2079. if (!obj.month && (obj.week || obj.dayOfYear)) {
  2080. utils.getDayOfYear(obj, dayOffset);
  2081. } else {
  2082. obj.dayOfYear = dayOffset[obj.month] + obj.day;
  2083. }
  2084. date = new Date(obj.year, obj.month, obj.day, obj.hours, obj.minutes, obj.seconds, obj.milliseconds);
  2085. if (obj.zone) {
  2086. utils.adjustForTimeZone(obj, date); // adjust (and calculate) for timezone
  2087. }
  2088. return date;
  2089. };
  2090. $P.ISO = {
  2091. regex : /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/,
  2092. parse : function (s) {
  2093. var time, data = s.match(this.regex);
  2094. if (!data || !data.length) {
  2095. return null;
  2096. }
  2097. time = utils.buildTimeObjectFromData(data);
  2098. if (!time.year || (!time.year && (!time.month && !time.day) && (!time.week && !time.dayOfYear)) ) {
  2099. return null;
  2100. }
  2101. return $P.processTimeObject(time);
  2102. }
  2103. };
  2104. $P.Numeric = {
  2105. isNumeric: function (e){return!isNaN(parseFloat(e))&&isFinite(e);},
  2106. regex: /\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i,
  2107. parse: function (s) {
  2108. var data, i,
  2109. time = {},
  2110. order = Date.CultureInfo.dateElementOrder.split("");
  2111. if (!(this.isNumeric(s)) || // if it's non-numeric OR
  2112. (s[0] === "+" && s[0] === "-")) { // It's an arithmatic string (eg +/-1000)
  2113. return null;
  2114. }
  2115. if (s.length < 5 && s.indexOf(".") < 0 && s.indexOf("/") < 0) { // assume it's just a year.
  2116. time.year = s;
  2117. return $P.processTimeObject(time);
  2118. }
  2119. data = s.match(this.regex);
  2120. if (!data || !data.length) {
  2121. return null;
  2122. }
  2123. for (i=0; i < order.length; i++) {
  2124. switch(order[i]) {
  2125. case "d":
  2126. time.day = data[i+1];
  2127. break;
  2128. case "m":
  2129. time.month = (data[i+1]-1);
  2130. break;
  2131. case "y":
  2132. time.year = data[i+1];
  2133. break;
  2134. }
  2135. }
  2136. return $P.processTimeObject(time);
  2137. }
  2138. };
  2139. $P.Normalizer = {
  2140. regexData: function () {
  2141. var $R = Date.CultureInfo.regexPatterns;
  2142. return utils.buildRegexData([
  2143. $R.tomorrow,
  2144. $R.yesterday,
  2145. [$R.past, $R.mon],
  2146. [$R.past, $R.tue],
  2147. [$R.past, $R.wed],
  2148. [$R.past, $R.thu],
  2149. [$R.past, $R.fri],
  2150. [$R.past, $R.sat],
  2151. [$R.past, $R.sun]
  2152. ]);
  2153. },
  2154. basicReplaceHash : function() {
  2155. var $R = Date.CultureInfo.regexPatterns;
  2156. return {
  2157. "January": $R.jan.source,
  2158. "February": $R.feb,
  2159. "March": $R.mar,
  2160. "April": $R.apr,
  2161. "May": $R.may,
  2162. "June": $R.jun,
  2163. "July": $R.jul,
  2164. "August": $R.aug,
  2165. "September": $R.sep,
  2166. "October": $R.oct,
  2167. "November": $R.nov,
  2168. "December": $R.dec,
  2169. "": /\bat\b/gi,
  2170. " ": /\s{2,}/,
  2171. "am": $R.inTheMorning,
  2172. "9am": $R.thisMorning,
  2173. "pm": $R.inTheEvening,
  2174. "7pm":$R.thisEvening
  2175. };
  2176. },
  2177. keys : function(){
  2178. return [
  2179. utils.getDateNthString(true, false, 1), // tomorrow
  2180. utils.getDateNthString(true, false, -1), // yesterday
  2181. utils.getDateNthString(false, true, "monday"), //last mon
  2182. utils.getDateNthString(false, true, "tuesday"), //last tues
  2183. utils.getDateNthString(false, true, "wednesday"), //last wed
  2184. utils.getDateNthString(false, true, "thursday"), //last thurs
  2185. utils.getDateNthString(false, true, "friday"), //last fri
  2186. utils.getDateNthString(false, true, "saturday"), //last sat
  2187. utils.getDateNthString(false, true, "sunday") //last sun
  2188. ];
  2189. },
  2190. buildRegexFunctions: function () {
  2191. var $R = Date.CultureInfo.regexPatterns;
  2192. var __ = Date.i18n.__;
  2193. var tomorrowRE = new RegExp("(\\b\\d\\d?("+__("AM")+"|"+__("PM")+")? )("+$R.tomorrow.source.slice(1)+")", "i"); // adapted tomorrow regex for AM PM relative dates
  2194. var todayRE = new RegExp($R.today.source + "(?!\\s*([+-]))\\b"); // today, but excludes the math operators (eg "today + 2h")
  2195. this.replaceFuncs = [
  2196. [todayRE, function (full) {
  2197. return (full.length > 1) ? Date.today().toString("d") : full;
  2198. }],
  2199. [tomorrowRE,
  2200. function(full, m1) {
  2201. var t = Date.today().addDays(1).toString("d");
  2202. return (t + " " + m1);
  2203. }],
  2204. [$R.amThisMorning, function(str, am){return am;}],
  2205. [$R.pmThisEvening, function(str, pm){return pm;}]
  2206. ];
  2207. },
  2208. buildReplaceData: function () {
  2209. this.buildRegexFunctions();
  2210. this.replaceHash = utils.addToHash(this.basicReplaceHash(), this.keys(), this.regexData());
  2211. },
  2212. stringReplaceFuncs: function (s) {
  2213. for (var i=0; i < this.replaceFuncs.length; i++) {
  2214. s = s.replace(this.replaceFuncs[i][0], this.replaceFuncs[i][1]);
  2215. }
  2216. return s;
  2217. },
  2218. parse: function (s) {
  2219. s = this.stringReplaceFuncs(s);
  2220. s = utils.multiReplace(s, this.replaceHash);
  2221. try {
  2222. var n = s.split(/([\s\-\.\,\/\x27]+)/);
  2223. if (n.length === 3 &&
  2224. $P.Numeric.isNumeric(n[0]) &&
  2225. $P.Numeric.isNumeric(n[2]) &&
  2226. (n[2].length >= 4)) {
  2227. // ok, so we're dealing with x/year. But that's not a full date.
  2228. // This fixes wonky dateElementOrder parsing when set to dmy order.
  2229. if (Date.CultureInfo.dateElementOrder[0] === "d") {
  2230. s = "1/" + n[0] + "/" + n[2]; // set to 1st of month and normalize the seperator
  2231. }
  2232. }
  2233. } catch (e) {}
  2234. return s;
  2235. }
  2236. };
  2237. $P.Normalizer.buildReplaceData();
  2238. }());
  2239. (function () {
  2240. var $P = Date.Parsing;
  2241. var _ = $P.Operators = {
  2242. //
  2243. // Tokenizers
  2244. //
  2245. rtoken: function (r) { // regex token
  2246. return function (s) {
  2247. var mx = s.match(r);
  2248. if (mx) {
  2249. return ([ mx[0], s.substring(mx[0].length) ]);
  2250. } else {
  2251. throw new $P.Exception(s);
  2252. }
  2253. };
  2254. },
  2255. token: function () { // whitespace-eating token
  2256. return function (s) {
  2257. return _.rtoken(new RegExp("^\\s*" + s + "\\s*"))(s);
  2258. };
  2259. },
  2260. stoken: function (s) { // string token
  2261. return _.rtoken(new RegExp("^" + s));
  2262. },
  2263. // Atomic Operators
  2264. until: function (p) {
  2265. return function (s) {
  2266. var qx = [], rx = null;
  2267. while (s.length) {
  2268. try {
  2269. rx = p.call(this, s);
  2270. } catch (e) {
  2271. qx.push(rx[0]);
  2272. s = rx[1];
  2273. continue;
  2274. }
  2275. break;
  2276. }
  2277. return [ qx, s ];
  2278. };
  2279. },
  2280. many: function (p) {
  2281. return function (s) {
  2282. var rx = [], r = null;
  2283. while (s.length) {
  2284. try {
  2285. r = p.call(this, s);
  2286. } catch (e) {
  2287. return [ rx, s ];
  2288. }
  2289. rx.push(r[0]);
  2290. s = r[1];
  2291. }
  2292. return [ rx, s ];
  2293. };
  2294. },
  2295. // generator operators -- see below
  2296. optional: function (p) {
  2297. return function (s) {
  2298. var r = null;
  2299. try {
  2300. r = p.call(this, s);
  2301. } catch (e) {
  2302. return [ null, s ];
  2303. }
  2304. return [ r[0], r[1] ];
  2305. };
  2306. },
  2307. not: function (p) {
  2308. return function (s) {
  2309. try {
  2310. p.call(this, s);
  2311. } catch (e) {
  2312. return [null, s];
  2313. }
  2314. throw new $P.Exception(s);
  2315. };
  2316. },
  2317. ignore: function (p) {
  2318. return p ?
  2319. function (s) {
  2320. var r = null;
  2321. r = p.call(this, s);
  2322. return [null, r[1]];
  2323. } : null;
  2324. },
  2325. product: function () {
  2326. var px = arguments[0],
  2327. qx = Array.prototype.slice.call(arguments, 1), rx = [];
  2328. for (var i = 0 ; i < px.length ; i++) {
  2329. rx.push(_.each(px[i], qx));
  2330. }
  2331. return rx;
  2332. },
  2333. cache: function (rule) {
  2334. var cache = {}, cache_length = 0, cache_keys = [], CACHE_MAX = Date.Config.CACHE_MAX || 100000, r = null;
  2335. var cacheCheck = function () {
  2336. if (cache_length === CACHE_MAX) {
  2337. // kill several keys, don't want to have to do this all the time...
  2338. for (var i=0; i < 10; i++) {
  2339. var key = cache_keys.shift();
  2340. if (key) {
  2341. delete cache[key];
  2342. cache_length--;
  2343. }
  2344. }
  2345. }
  2346. };
  2347. return function (s) {
  2348. cacheCheck();
  2349. try {
  2350. r = cache[s] = (cache[s] || rule.call(this, s));
  2351. } catch (e) {
  2352. r = cache[s] = e;
  2353. }
  2354. cache_length++;
  2355. cache_keys.push(s);
  2356. if (r instanceof $P.Exception) {
  2357. throw r;
  2358. } else {
  2359. return r;
  2360. }
  2361. };
  2362. },
  2363. // vector operators -- see below
  2364. any: function () {
  2365. var px = arguments;
  2366. return function (s) {
  2367. var r = null;
  2368. for (var i = 0; i < px.length; i++) {
  2369. if (px[i] == null) {
  2370. continue;
  2371. }
  2372. try {
  2373. r = (px[i].call(this, s));
  2374. } catch (e) {
  2375. r = null;
  2376. }
  2377. if (r) {
  2378. return r;
  2379. }
  2380. }
  2381. throw new $P.Exception(s);
  2382. };
  2383. },
  2384. each: function () {
  2385. var px = arguments;
  2386. return function (s) {
  2387. var rx = [], r = null;
  2388. for (var i = 0; i < px.length ; i++) {
  2389. if (px[i] == null) {
  2390. continue;
  2391. }
  2392. try {
  2393. r = (px[i].call(this, s));
  2394. } catch (e) {
  2395. throw new $P.Exception(s);
  2396. }
  2397. rx.push(r[0]);
  2398. s = r[1];
  2399. }
  2400. return [ rx, s];
  2401. };
  2402. },
  2403. all: function () {
  2404. var px = arguments, _ = _;
  2405. return _.each(_.optional(px));
  2406. },
  2407. // delimited operators
  2408. sequence: function (px, d, c) {
  2409. d = d || _.rtoken(/^\s*/);
  2410. c = c || null;
  2411. if (px.length === 1) {
  2412. return px[0];
  2413. }
  2414. return function (s) {
  2415. var r = null, q = null;
  2416. var rx = [];
  2417. for (var i = 0; i < px.length ; i++) {
  2418. try {
  2419. r = px[i].call(this, s);
  2420. } catch (e) {
  2421. break;
  2422. }
  2423. rx.push(r[0]);
  2424. try {
  2425. q = d.call(this, r[1]);
  2426. } catch (ex) {
  2427. q = null;
  2428. break;
  2429. }
  2430. s = q[1];
  2431. }
  2432. if (!r) {
  2433. throw new $P.Exception(s);
  2434. }
  2435. if (q) {
  2436. throw new $P.Exception(q[1]);
  2437. }
  2438. if (c) {
  2439. try {
  2440. r = c.call(this, r[1]);
  2441. } catch (ey) {
  2442. throw new $P.Exception(r[1]);
  2443. }
  2444. }
  2445. return [ rx, (r?r[1]:s) ];
  2446. };
  2447. },
  2448. //
  2449. // Composite Operators
  2450. //
  2451. between: function (d1, p, d2) {
  2452. d2 = d2 || d1;
  2453. var _fn = _.each(_.ignore(d1), p, _.ignore(d2));
  2454. return function (s) {
  2455. var rx = _fn.call(this, s);
  2456. return [[rx[0][0], r[0][2]], rx[1]];
  2457. };
  2458. },
  2459. list: function (p, d, c) {
  2460. d = d || _.rtoken(/^\s*/);
  2461. c = c || null;
  2462. return (p instanceof Array ?
  2463. _.each(_.product(p.slice(0, -1), _.ignore(d)), p.slice(-1), _.ignore(c)) :
  2464. _.each(_.many(_.each(p, _.ignore(d))), px, _.ignore(c)));
  2465. },
  2466. set: function (px, d, c) {
  2467. d = d || _.rtoken(/^\s*/);
  2468. c = c || null;
  2469. return function (s) {
  2470. // r is the current match, best the current 'best' match
  2471. // which means it parsed the most amount of input
  2472. var r = null, p = null, q = null, rx = null, best = [[], s], last = false;
  2473. // go through the rules in the given set
  2474. for (var i = 0; i < px.length ; i++) {
  2475. // last is a flag indicating whether this must be the last element
  2476. // if there is only 1 element, then it MUST be the last one
  2477. q = null;
  2478. p = null;
  2479. r = null;
  2480. last = (px.length === 1);
  2481. // first, we try simply to match the current pattern
  2482. // if not, try the next pattern
  2483. try {
  2484. r = px[i].call(this, s);
  2485. } catch (e) {
  2486. continue;
  2487. }
  2488. // since we are matching against a set of elements, the first
  2489. // thing to do is to add r[0] to matched elements
  2490. rx = [[r[0]], r[1]];
  2491. // if we matched and there is still input to parse and
  2492. // we don't already know this is the last element,
  2493. // we're going to next check for the delimiter ...
  2494. // if there's none, or if there's no input left to parse
  2495. // than this must be the last element after all ...
  2496. if (r[1].length > 0 && ! last) {
  2497. try {
  2498. q = d.call(this, r[1]);
  2499. } catch (ex) {
  2500. last = true;
  2501. }
  2502. } else {
  2503. last = true;
  2504. }
  2505. // if we parsed the delimiter and now there's no more input,
  2506. // that means we shouldn't have parsed the delimiter at all
  2507. // so don't update r and mark this as the last element ...
  2508. if (!last && q[1].length === 0) {
  2509. last = true;
  2510. }
  2511. // so, if this isn't the last element, we're going to see if
  2512. // we can get any more matches from the remaining (unmatched)
  2513. // elements ...
  2514. if (!last) {
  2515. // build a list of the remaining rules we can match against,
  2516. // i.e., all but the one we just matched against
  2517. var qx = [];
  2518. for (var j = 0; j < px.length ; j++) {
  2519. if (i !== j) {
  2520. qx.push(px[j]);
  2521. }
  2522. }
  2523. // now invoke recursively set with the remaining input
  2524. // note that we don't include the closing delimiter ...
  2525. // we'll check for that ourselves at the end
  2526. p = _.set(qx, d).call(this, q[1]);
  2527. // if we got a non-empty set as a result ...
  2528. // (otw rx already contains everything we want to match)
  2529. if (p[0].length > 0) {
  2530. // update current result, which is stored in rx ...
  2531. // basically, pick up the remaining text from p[1]
  2532. // and concat the result from p[0] so that we don't
  2533. // get endless nesting ...
  2534. rx[0] = rx[0].concat(p[0]);
  2535. rx[1] = p[1];
  2536. }
  2537. }
  2538. // at this point, rx either contains the last matched element
  2539. // or the entire matched set that starts with this element.
  2540. // now we just check to see if this variation is better than
  2541. // our best so far, in terms of how much of the input is parsed
  2542. if (rx[1].length < best[1].length) {
  2543. best = rx;
  2544. }
  2545. // if we've parsed all the input, then we're finished
  2546. if (best[1].length === 0) {
  2547. break;
  2548. }
  2549. }
  2550. // so now we've either gone through all the patterns trying them
  2551. // as the initial match; or we found one that parsed the entire
  2552. // input string ...
  2553. // if best has no matches, just return empty set ...
  2554. if (best[0].length === 0) {
  2555. return best;
  2556. }
  2557. // if a closing delimiter is provided, then we have to check it also
  2558. if (c) {
  2559. // we try this even if there is no remaining input because the pattern
  2560. // may well be optional or match empty input ...
  2561. try {
  2562. q = c.call(this, best[1]);
  2563. } catch (ey) {
  2564. throw new $P.Exception(best[1]);
  2565. }
  2566. // it parsed ... be sure to update the best match remaining input
  2567. best[1] = q[1];
  2568. }
  2569. // if we're here, either there was no closing delimiter or we parsed it
  2570. // so now we have the best match; just return it!
  2571. return best;
  2572. };
  2573. },
  2574. forward: function (gr, fname) {
  2575. return function (s) {
  2576. return gr[fname].call(this, s);
  2577. };
  2578. },
  2579. //
  2580. // Translation Operators
  2581. //
  2582. replace: function (rule, repl) {
  2583. return function (s) {
  2584. var r = rule.call(this, s);
  2585. return [repl, r[1]];
  2586. };
  2587. },
  2588. process: function (rule, fn) {
  2589. return function (s) {
  2590. var r = rule.call(this, s);
  2591. return [fn.call(this, r[0]), r[1]];
  2592. };
  2593. },
  2594. min: function (min, rule) {
  2595. return function (s) {
  2596. var rx = rule.call(this, s);
  2597. if (rx[0].length < min) {
  2598. throw new $P.Exception(s);
  2599. }
  2600. return rx;
  2601. };
  2602. }
  2603. };
  2604. // Generator Operators And Vector Operators
  2605. // Generators are operators that have a signature of F(R) => R,
  2606. // taking a given rule and returning another rule, such as
  2607. // ignore, which parses a given rule and throws away the result.
  2608. // Vector operators are those that have a signature of F(R1,R2,...) => R,
  2609. // take a list of rules and returning a new rule, such as each.
  2610. // Generator operators are converted (via the following _generator
  2611. // function) into functions that can also take a list or array of rules
  2612. // and return an array of new rules as though the function had been
  2613. // called on each rule in turn (which is what actually happens).
  2614. // This allows generators to be used with vector operators more easily.
  2615. // Example:
  2616. // each(ignore(foo, bar)) instead of each(ignore(foo), ignore(bar))
  2617. // This also turns generators into vector operators, which allows
  2618. // constructs like:
  2619. // not(cache(foo, bar))
  2620. var _generator = function (op) {
  2621. function gen() {
  2622. var args = null, rx = [], px, i;
  2623. if (arguments.length > 1) {
  2624. args = Array.prototype.slice.call(arguments);
  2625. } else if (arguments[0] instanceof Array) {
  2626. args = arguments[0];
  2627. }
  2628. if (args) {
  2629. px = args.shift();
  2630. if (px.length > 0) {
  2631. args.unshift(px[i]);
  2632. rx.push(op.apply(null, args));
  2633. args.shift();
  2634. return rx;
  2635. }
  2636. } else {
  2637. return op.apply(null, arguments);
  2638. }
  2639. }
  2640. return gen;
  2641. };
  2642. var gx = "optional not ignore cache".split(/\s/);
  2643. for (var i = 0 ; i < gx.length ; i++) {
  2644. _[gx[i]] = _generator(_[gx[i]]);
  2645. }
  2646. var _vector = function (op) {
  2647. return function () {
  2648. if (arguments[0] instanceof Array) {
  2649. return op.apply(null, arguments[0]);
  2650. } else {
  2651. return op.apply(null, arguments);
  2652. }
  2653. };
  2654. };
  2655. var vx = "each any all".split(/\s/);
  2656. for (var j = 0 ; j < vx.length ; j++) {
  2657. _[vx[j]] = _vector(_[vx[j]]);
  2658. }
  2659. }());
  2660. (function () {
  2661. var $D = Date;
  2662. var flattenAndCompact = function (ax) {
  2663. var rx = [];
  2664. for (var i = 0; i < ax.length; i++) {
  2665. if (ax[i] instanceof Array) {
  2666. rx = rx.concat(flattenAndCompact(ax[i]));
  2667. } else {
  2668. if (ax[i]) {
  2669. rx.push(ax[i]);
  2670. }
  2671. }
  2672. }
  2673. return rx;
  2674. };
  2675. var parseMeridian = function () {
  2676. if (this.meridian && (this.hour || this.hour === 0)) {
  2677. if (this.meridian === "a" && this.hour > 11 && Date.Config.strict24hr){
  2678. throw "Invalid hour and meridian combination";
  2679. } else if (this.meridian === "p" && this.hour < 12 && Date.Config.strict24hr){
  2680. throw "Invalid hour and meridian combination";
  2681. } else if (this.meridian === "p" && this.hour < 12) {
  2682. this.hour = this.hour + 12;
  2683. } else if (this.meridian === "a" && this.hour === 12) {
  2684. this.hour = 0;
  2685. }
  2686. }
  2687. };
  2688. var setDefaults = function () {
  2689. var now = new Date();
  2690. if ((this.hour || this.minute) && (!this.month && !this.year && !this.day)) {
  2691. this.day = now.getDate();
  2692. }
  2693. if (!this.year) {
  2694. this.year = now.getFullYear();
  2695. }
  2696. if (!this.month && this.month !== 0) {
  2697. this.month = now.getMonth();
  2698. }
  2699. if (!this.day) {
  2700. this.day = 1;
  2701. }
  2702. if (!this.hour) {
  2703. this.hour = 0;
  2704. }
  2705. if (!this.minute) {
  2706. this.minute = 0;
  2707. }
  2708. if (!this.second) {
  2709. this.second = 0;
  2710. }
  2711. if (!this.millisecond) {
  2712. this.millisecond = 0;
  2713. }
  2714. };
  2715. var finishUtils = {
  2716. getToday: function () {
  2717. if (this.now || "hour minute second".indexOf(this.unit) !== -1) {
  2718. return new Date();
  2719. } else {
  2720. return $D.today();
  2721. }
  2722. },
  2723. setDaysFromWeekday: function (today, orient){
  2724. var gap;
  2725. orient = orient || 1;
  2726. this.unit = "day";
  2727. gap = ($D.getDayNumberFromName(this.weekday) - today.getDay());
  2728. this.days = gap ? ((gap + (orient * 7)) % 7) : (orient * 7);
  2729. return this;
  2730. },
  2731. setMonthsFromMonth: function (today, orient) {
  2732. var gap;
  2733. orient = orient || 1;
  2734. this.unit = "month";
  2735. gap = (this.month - today.getMonth());
  2736. this.months = gap ? ((gap + (orient * 12)) % 12) : (orient * 12);
  2737. this.month = null;
  2738. return this;
  2739. },
  2740. setDMYFromWeekday: function () {
  2741. var d = Date[this.weekday]();
  2742. this.day = d.getDate();
  2743. if (!this.month) {
  2744. this.month = d.getMonth();
  2745. }
  2746. this.year = d.getFullYear();
  2747. return this;
  2748. },
  2749. setUnitValue: function (orient) {
  2750. if (!this.value && this.operator && this.operator !== null && this[this.unit + "s"] && this[this.unit + "s"] !== null) {
  2751. this[this.unit + "s"] = this[this.unit + "s"] + ((this.operator === "add") ? 1 : -1) + (this.value||0) * orient;
  2752. } else if (this[this.unit + "s"] == null || this.operator != null) {
  2753. if (!this.value) {
  2754. this.value = 1;
  2755. }
  2756. this[this.unit + "s"] = this.value * orient;
  2757. }
  2758. },
  2759. generateDateFromWeeks: function () {
  2760. var weekday = (this.weekday !== undefined) ? this.weekday : "today";
  2761. var d = Date[weekday]().addWeeks(this.weeks);
  2762. if (this.now) {
  2763. d.setTimeToNow();
  2764. }
  2765. return d;
  2766. }
  2767. };
  2768. $D.Translator = {
  2769. hour: function (s) {
  2770. return function () {
  2771. this.hour = Number(s);
  2772. };
  2773. },
  2774. minute: function (s) {
  2775. return function () {
  2776. this.minute = Number(s);
  2777. };
  2778. },
  2779. second: function (s) {
  2780. return function () {
  2781. this.second = Number(s);
  2782. };
  2783. },
  2784. /* for ss.s format */
  2785. secondAndMillisecond: function (s) {
  2786. return function () {
  2787. var mx = s.match(/^([0-5][0-9])\.([0-9]{1,3})/);
  2788. this.second = Number(mx[1]);
  2789. this.millisecond = Number(mx[2]);
  2790. };
  2791. },
  2792. meridian: function (s) {
  2793. return function () {
  2794. this.meridian = s.slice(0, 1).toLowerCase();
  2795. };
  2796. },
  2797. timezone: function (s) {
  2798. return function () {
  2799. var n = s.replace(/[^\d\+\-]/g, "");
  2800. if (n.length) {
  2801. this.timezoneOffset = Number(n);
  2802. } else {
  2803. this.timezone = s.toLowerCase();
  2804. }
  2805. };
  2806. },
  2807. day: function (x) {
  2808. var s = x[0];
  2809. return function () {
  2810. this.day = Number(s.match(/\d+/)[0]);
  2811. if (this.day < 1) {
  2812. throw "invalid day";
  2813. }
  2814. };
  2815. },
  2816. month: function (s) {
  2817. return function () {
  2818. this.month = (s.length === 3) ? "jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4 : Number(s) - 1;
  2819. if (this.month < 0) {
  2820. throw "invalid month";
  2821. }
  2822. };
  2823. },
  2824. year: function (s) {
  2825. return function () {
  2826. var n = Number(s);
  2827. this.year = ((s.length > 2) ? n :
  2828. (n + (((n + 2000) < Date.CultureInfo.twoDigitYearMax) ? 2000 : 1900)));
  2829. };
  2830. },
  2831. rday: function (s) {
  2832. return function () {
  2833. switch (s) {
  2834. case "yesterday":
  2835. this.days = -1;
  2836. break;
  2837. case "tomorrow":
  2838. this.days = 1;
  2839. break;
  2840. case "today":
  2841. this.days = 0;
  2842. break;
  2843. case "now":
  2844. this.days = 0;
  2845. this.now = true;
  2846. break;
  2847. }
  2848. };
  2849. },
  2850. finishExact: function (x) {
  2851. var d;
  2852. x = (x instanceof Array) ? x : [x];
  2853. for (var i = 0 ; i < x.length ; i++) {
  2854. if (x[i]) {
  2855. x[i].call(this);
  2856. }
  2857. }
  2858. setDefaults.call(this);
  2859. parseMeridian.call(this);
  2860. if (this.day > $D.getDaysInMonth(this.year, this.month)) {
  2861. throw new RangeError(this.day + " is not a valid value for days.");
  2862. }
  2863. d = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond);
  2864. if (this.year < 100) {
  2865. d.setFullYear(this.year); // means years less that 100 are process correctly. JS will parse it otherwise as 1900-1999.
  2866. }
  2867. if (this.timezone) {
  2868. d.set({ timezone: this.timezone });
  2869. } else if (this.timezoneOffset) {
  2870. d.set({ timezoneOffset: this.timezoneOffset });
  2871. }
  2872. return d;
  2873. },
  2874. finish: function (x) {
  2875. var today, expression, orient, temp;
  2876. x = (x instanceof Array) ? flattenAndCompact(x) : [ x ];
  2877. if (x.length === 0) {
  2878. return null;
  2879. }
  2880. for (var i = 0 ; i < x.length ; i++) {
  2881. if (typeof x[i] === "function") {
  2882. x[i].call(this);
  2883. }
  2884. }
  2885. if (this.now && !this.unit && !this.operator) {
  2886. return new Date();
  2887. } else {
  2888. today = finishUtils.getToday.call(this);
  2889. }
  2890. expression = !!(this.days && this.days !== null || this.orient || this.operator);
  2891. orient = ((this.orient === "past" || this.operator === "subtract") ? -1 : 1);
  2892. if (this.month && this.unit === "week") {
  2893. this.value = this.month + 1;
  2894. delete this.month;
  2895. delete this.day;
  2896. }
  2897. if ((this.month || this.month === 0) && "year day hour minute second".indexOf(this.unit) !== -1) {
  2898. if (!this.value) {
  2899. this.value = this.month + 1;
  2900. }
  2901. this.month = null;
  2902. expression = true;
  2903. }
  2904. if (!expression && this.weekday && !this.day && !this.days) {
  2905. finishUtils.setDMYFromWeekday.call(this);
  2906. }
  2907. if (expression && this.weekday && this.unit !== "month" && this.unit !== "week") {
  2908. finishUtils.setDaysFromWeekday.call(this, today, orient);
  2909. }
  2910. if (this.weekday && this.unit !== "week" && !this.day && !this.days) {
  2911. temp = Date[this.weekday]();
  2912. this.day = temp.getDate();
  2913. if (temp.getMonth() !== today.getMonth()) {
  2914. this.month = temp.getMonth();
  2915. }
  2916. }
  2917. if (this.month && this.unit === "day" && this.operator) {
  2918. if (!this.value) {
  2919. this.value = (this.month + 1);
  2920. }
  2921. this.month = null;
  2922. }
  2923. if (this.value != null && this.month != null && this.year != null) {
  2924. this.day = this.value * 1;
  2925. }
  2926. if (this.month && !this.day && this.value) {
  2927. today.set({ day: this.value * 1 });
  2928. if (!expression) {
  2929. this.day = this.value * 1;
  2930. }
  2931. }
  2932. if (!this.month && this.value && this.unit === "month" && !this.now) {
  2933. this.month = this.value;
  2934. expression = true;
  2935. }
  2936. if (expression && (this.month || this.month === 0) && this.unit !== "year") {
  2937. finishUtils.setMonthsFromMonth.call(this, today, orient);
  2938. }
  2939. if (!this.unit) {
  2940. this.unit = "day";
  2941. }
  2942. finishUtils.setUnitValue.call(this, orient);
  2943. parseMeridian.call(this);
  2944. if ((this.month || this.month === 0) && !this.day) {
  2945. this.day = 1;
  2946. }
  2947. if (!this.orient && !this.operator && this.unit === "week" && this.value && !this.day && !this.month) {
  2948. return Date.today().setWeek(this.value);
  2949. }
  2950. if (this.unit === "week" && this.weeks && !this.day && !this.month) {
  2951. return finishUtils.generateDateFromWeeks.call(this);
  2952. }
  2953. if (expression && this.timezone && this.day && this.days) {
  2954. this.day = this.days;
  2955. }
  2956. if (expression){
  2957. today.add(this);
  2958. } else {
  2959. today.set(this);
  2960. }
  2961. if (this.timezone) {
  2962. this.timezone = this.timezone.toUpperCase();
  2963. var offset = $D.getTimezoneOffset(this.timezone);
  2964. var timezone;
  2965. if (today.hasDaylightSavingTime()) {
  2966. // lets check that we're being sane with timezone setting
  2967. timezone = $D.getTimezoneAbbreviation(offset, today.isDaylightSavingTime());
  2968. if (timezone !== this.timezone) {
  2969. // bugger, we're in a place where things like EST vs EDT matters.
  2970. if (today.isDaylightSavingTime()) {
  2971. today.addHours(-1);
  2972. } else {
  2973. today.addHours(1);
  2974. }
  2975. }
  2976. }
  2977. today.setTimezoneOffset(offset);
  2978. }
  2979. return today;
  2980. }
  2981. };
  2982. }());
  2983. (function () {
  2984. var $D = Date;
  2985. $D.Grammar = {};
  2986. var _ = $D.Parsing.Operators, g = $D.Grammar, t = $D.Translator, _fn;
  2987. // Allow rolling up into general purpose rules
  2988. _fn = function () {
  2989. return _.each(_.any.apply(null, arguments), _.not(g.ctoken2("timeContext")));
  2990. };
  2991. g.datePartDelimiter = _.rtoken(/^([\s\-\.\,\/\x27]+)/);
  2992. g.timePartDelimiter = _.stoken(":");
  2993. g.whiteSpace = _.rtoken(/^\s*/);
  2994. g.generalDelimiter = _.rtoken(/^(([\s\,]|at|@|on)+)/);
  2995. var _C = {};
  2996. g.ctoken = function (keys) {
  2997. var fn = _C[keys];
  2998. if (! fn) {
  2999. var c = Date.CultureInfo.regexPatterns;
  3000. var kx = keys.split(/\s+/), px = [];
  3001. for (var i = 0; i < kx.length ; i++) {
  3002. px.push(_.replace(_.rtoken(c[kx[i]]), kx[i]));
  3003. }
  3004. fn = _C[keys] = _.any.apply(null, px);
  3005. }
  3006. return fn;
  3007. };
  3008. g.ctoken2 = function (key) {
  3009. return _.rtoken(Date.CultureInfo.regexPatterns[key]);
  3010. };
  3011. var cacheProcessRtoken = function (key, token, type, eachToken) {
  3012. if (eachToken) {
  3013. g[key] = _.cache(_.process(_.each(_.rtoken(token),_.optional(g.ctoken2(eachToken))), type));
  3014. } else {
  3015. g[key] = _.cache(_.process(_.rtoken(token), type));
  3016. }
  3017. };
  3018. var cacheProcessCtoken = function (token, type) {
  3019. return _.cache(_.process(g.ctoken2(token), type));
  3020. };
  3021. var _F = {}; //function cache
  3022. var _get = function (f) {
  3023. _F[f] = (_F[f] || g.format(f)[0]);
  3024. return _F[f];
  3025. };
  3026. g.allformats = function (fx) {
  3027. var rx = [];
  3028. if (fx instanceof Array) {
  3029. for (var i = 0; i < fx.length; i++) {
  3030. rx.push(_get(fx[i]));
  3031. }
  3032. } else {
  3033. rx.push(_get(fx));
  3034. }
  3035. return rx;
  3036. };
  3037. g.formats = function (fx) {
  3038. if (fx instanceof Array) {
  3039. var rx = [];
  3040. for (var i = 0 ; i < fx.length ; i++) {
  3041. rx.push(_get(fx[i]));
  3042. }
  3043. return _.any.apply(null, rx);
  3044. } else {
  3045. return _get(fx);
  3046. }
  3047. };
  3048. var grammarFormats = {
  3049. timeFormats: function(){
  3050. var i,
  3051. RTokenKeys = [
  3052. "h",
  3053. "hh",
  3054. "H",
  3055. "HH",
  3056. "m",
  3057. "mm",
  3058. "s",
  3059. "ss",
  3060. "ss.s",
  3061. "z",
  3062. "zz"
  3063. ],
  3064. RToken = [
  3065. /^(0[0-9]|1[0-2]|[1-9])/,
  3066. /^(0[0-9]|1[0-2])/,
  3067. /^([0-1][0-9]|2[0-3]|[0-9])/,
  3068. /^([0-1][0-9]|2[0-3])/,
  3069. /^([0-5][0-9]|[0-9])/,
  3070. /^[0-5][0-9]/,
  3071. /^([0-5][0-9]|[0-9])/,
  3072. /^[0-5][0-9]/,
  3073. /^[0-5][0-9]\.[0-9]{1,3}/,
  3074. /^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/,
  3075. /^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/
  3076. ],
  3077. tokens = [
  3078. t.hour,
  3079. t.hour,
  3080. t.hour,
  3081. t.minute,
  3082. t.minute,
  3083. t.second,
  3084. t.second,
  3085. t.secondAndMillisecond,
  3086. t.timezone,
  3087. t.timezone,
  3088. t.timezone
  3089. ];
  3090. for (i=0; i < RTokenKeys.length; i++) {
  3091. cacheProcessRtoken(RTokenKeys[i], RToken[i], tokens[i]);
  3092. }
  3093. g.hms = _.cache(_.sequence([g.H, g.m, g.s], g.timePartDelimiter));
  3094. g.t = cacheProcessCtoken("shortMeridian", t.meridian);
  3095. g.tt = cacheProcessCtoken("longMeridian", t.meridian);
  3096. g.zzz = cacheProcessCtoken("timezone", t.timezone);
  3097. g.timeSuffix = _.each(_.ignore(g.whiteSpace), _.set([ g.tt, g.zzz ]));
  3098. g.time = _.each(_.optional(_.ignore(_.stoken("T"))), g.hms, g.timeSuffix);
  3099. },
  3100. dateFormats: function () {
  3101. // pre-loaded rules for different date part order preferences
  3102. var _setfn = function () {
  3103. return _.set(arguments, g.datePartDelimiter);
  3104. };
  3105. var i,
  3106. RTokenKeys = [
  3107. "d",
  3108. "dd",
  3109. "M",
  3110. "MM",
  3111. "y",
  3112. "yy",
  3113. "yyy",
  3114. "yyyy"
  3115. ],
  3116. RToken = [
  3117. /^([0-2]\d|3[0-1]|\d)/,
  3118. /^([0-2]\d|3[0-1])/,
  3119. /^(1[0-2]|0\d|\d)/,
  3120. /^(1[0-2]|0\d)/,
  3121. /^(\d+)/,
  3122. /^(\d\d)/,
  3123. /^(\d\d?\d?\d?)/,
  3124. /^(\d\d\d\d)/
  3125. ],
  3126. tokens = [
  3127. t.day,
  3128. t.day,
  3129. t.month,
  3130. t.month,
  3131. t.year,
  3132. t.year,
  3133. t.year,
  3134. t.year
  3135. ],
  3136. eachToken = [
  3137. "ordinalSuffix",
  3138. "ordinalSuffix"
  3139. ];
  3140. for (i=0; i < RTokenKeys.length; i++) {
  3141. cacheProcessRtoken(RTokenKeys[i], RToken[i], tokens[i], eachToken[i]);
  3142. }
  3143. g.MMM = g.MMMM = _.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"), t.month));
  3144. g.ddd = g.dddd = _.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),
  3145. function (s) {
  3146. return function () {
  3147. this.weekday = s;
  3148. };
  3149. }
  3150. ));
  3151. g.day = _fn(g.d, g.dd);
  3152. g.month = _fn(g.M, g.MMM);
  3153. g.year = _fn(g.yyyy, g.yy);
  3154. g.mdy = _setfn(g.ddd, g.month, g.day, g.year);
  3155. g.ymd = _setfn(g.ddd, g.year, g.month, g.day);
  3156. g.dmy = _setfn(g.ddd, g.day, g.month, g.year);
  3157. g.date = function (s) {
  3158. return ((g[Date.CultureInfo.dateElementOrder] || g.mdy).call(this, s));
  3159. };
  3160. },
  3161. relative: function () {
  3162. // relative date / time expressions
  3163. g.orientation = _.process(g.ctoken("past future"),
  3164. function (s) {
  3165. return function () {
  3166. this.orient = s;
  3167. };
  3168. }
  3169. );
  3170. g.operator = _.process(g.ctoken("add subtract"),
  3171. function (s) {
  3172. return function () {
  3173. this.operator = s;
  3174. };
  3175. }
  3176. );
  3177. g.rday = _.process(g.ctoken("yesterday tomorrow today now"), t.rday);
  3178. g.unit = _.process(g.ctoken("second minute hour day week month year"),
  3179. function (s) {
  3180. return function () {
  3181. this.unit = s;
  3182. };
  3183. }
  3184. );
  3185. }
  3186. };
  3187. g.buildGrammarFormats = function () {
  3188. // these need to be rebuilt every time the language changes.
  3189. _C = {};
  3190. grammarFormats.timeFormats();
  3191. grammarFormats.dateFormats();
  3192. grammarFormats.relative();
  3193. g.value = _.process(_.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/),
  3194. function (s) {
  3195. return function () {
  3196. this.value = s.replace(/\D/g, "");
  3197. };
  3198. }
  3199. );
  3200. g.expression = _.set([g.rday, g.operator, g.value, g.unit, g.orientation, g.ddd, g.MMM ]);
  3201. g.format = _.process(_.many(
  3202. _.any(
  3203. // translate format specifiers into grammar rules
  3204. _.process(
  3205. _.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),
  3206. function (fmt) {
  3207. if (g[fmt]) {
  3208. return g[fmt];
  3209. } else {
  3210. throw $D.Parsing.Exception(fmt);
  3211. }
  3212. }
  3213. ),
  3214. // translate separator tokens into token rules
  3215. _.process(_.rtoken(/^[^dMyhHmstz]+/), // all legal separators
  3216. function (s) {
  3217. return _.ignore(_.stoken(s));
  3218. }
  3219. )
  3220. )
  3221. ),
  3222. // construct the parser ...
  3223. function (rules) {
  3224. return _.process(_.each.apply(null, rules), t.finishExact);
  3225. }
  3226. );
  3227. // starting rule for general purpose grammar
  3228. g._start = _.process(_.set([ g.date, g.time, g.expression ],
  3229. g.generalDelimiter, g.whiteSpace), t.finish);
  3230. };
  3231. g.buildGrammarFormats();
  3232. // parsing date format specifiers - ex: "h:m:s tt"
  3233. // this little guy will generate a custom parser based
  3234. // on the format string, ex: g.format("h:m:s tt")
  3235. // check for these formats first
  3236. g._formats = g.formats([
  3237. "\"yyyy-MM-ddTHH:mm:ssZ\"",
  3238. "yyyy-MM-ddTHH:mm:ss.sz",
  3239. "yyyy-MM-ddTHH:mm:ssZ",
  3240. "yyyy-MM-ddTHH:mm:ssz",
  3241. "yyyy-MM-ddTHH:mm:ss",
  3242. "yyyy-MM-ddTHH:mmZ",
  3243. "yyyy-MM-ddTHH:mmz",
  3244. "yyyy-MM-ddTHH:mm",
  3245. "ddd, MMM dd, yyyy H:mm:ss tt",
  3246. "ddd MMM d yyyy HH:mm:ss zzz",
  3247. "MMddyyyy",
  3248. "ddMMyyyy",
  3249. "Mddyyyy",
  3250. "ddMyyyy",
  3251. "Mdyyyy",
  3252. "dMyyyy",
  3253. "yyyy",
  3254. "Mdyy",
  3255. "dMyy",
  3256. "d"
  3257. ]);
  3258. // real starting rule: tries selected formats first,
  3259. // then general purpose rule
  3260. g.start = function (s) {
  3261. try {
  3262. var r = g._formats.call({}, s);
  3263. if (r[1].length === 0) {
  3264. return r;
  3265. }
  3266. } catch (e) {}
  3267. return g._start.call({}, s);
  3268. };
  3269. }());
  3270. (function () {
  3271. var $D = Date;
  3272. /**
  3273. * @desc Converts the specified string value into its JavaScript Date equivalent using CultureInfo specific format information.
  3274. *
  3275. * Example
  3276. <pre><code>
  3277. ///////////
  3278. // Dates //
  3279. ///////////
  3280. // 15-Oct-2004
  3281. var d1 = Date.parse("10/15/2004");
  3282. // 15-Oct-2004
  3283. var d1 = Date.parse("15-Oct-2004");
  3284. // 15-Oct-2004
  3285. var d1 = Date.parse("2004.10.15");
  3286. //Fri Oct 15, 2004
  3287. var d1 = Date.parse("Fri Oct 15, 2004");
  3288. ///////////
  3289. // Times //
  3290. ///////////
  3291. // Today at 10 PM.
  3292. var d1 = Date.parse("10 PM");
  3293. // Today at 10:30 PM.
  3294. var d1 = Date.parse("10:30 P.M.");
  3295. // Today at 6 AM.
  3296. var d1 = Date.parse("06am");
  3297. /////////////////////
  3298. // Dates and Times //
  3299. /////////////////////
  3300. // 8-July-2004 @ 10:30 PM
  3301. var d1 = Date.parse("July 8th, 2004, 10:30 PM");
  3302. // 1-July-2004 @ 10:30 PM
  3303. var d1 = Date.parse("2004-07-01T22:30:00");
  3304. ////////////////////
  3305. // Relative Dates //
  3306. ////////////////////
  3307. // Returns today's date. The string "today" is culture specific.
  3308. var d1 = Date.parse("today");
  3309. // Returns yesterday's date. The string "yesterday" is culture specific.
  3310. var d1 = Date.parse("yesterday");
  3311. // Returns the date of the next thursday.
  3312. var d1 = Date.parse("Next thursday");
  3313. // Returns the date of the most previous monday.
  3314. var d1 = Date.parse("last monday");
  3315. // Returns today's day + one year.
  3316. var d1 = Date.parse("next year");
  3317. ///////////////
  3318. // Date Math //
  3319. ///////////////
  3320. // Today + 2 days
  3321. var d1 = Date.parse("t+2");
  3322. // Today + 2 days
  3323. var d1 = Date.parse("today + 2 days");
  3324. // Today + 3 months
  3325. var d1 = Date.parse("t+3m");
  3326. // Today - 1 year
  3327. var d1 = Date.parse("today - 1 year");
  3328. // Today - 1 year
  3329. var d1 = Date.parse("t-1y");
  3330. /////////////////////////////
  3331. // Partial Dates and Times //
  3332. /////////////////////////////
  3333. // July 15th of this year.
  3334. var d1 = Date.parse("July 15");
  3335. // 15th day of current day and year.
  3336. var d1 = Date.parse("15");
  3337. // July 1st of current year at 10pm.
  3338. var d1 = Date.parse("7/1 10pm");
  3339. </code></pre>
  3340. *
  3341. * @param {String} The string value to convert into a Date object [Required]
  3342. * @return {Date} A Date object or null if the string cannot be converted into a Date.
  3343. */
  3344. var parseUtils = {
  3345. removeOrds: function (s) {
  3346. ords = s.match(/\b(\d+)(?:st|nd|rd|th)\b/); // find ordinal matches
  3347. s = ((ords && ords.length === 2) ? s.replace(ords[0], ords[1]) : s);
  3348. return s;
  3349. },
  3350. grammarParser: function (s) {
  3351. var r = null;
  3352. try {
  3353. r = $D.Grammar.start.call({}, s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
  3354. } catch (e) {
  3355. return null;
  3356. }
  3357. return ((r[1].length === 0) ? r[0] : null);
  3358. },
  3359. nativeFallback: function(s) {
  3360. var t;
  3361. try {
  3362. // ok we haven't parsed it, last ditch attempt with the built-in parser.
  3363. t = Date._parse(s);
  3364. return (t || t === 0) ? new Date(t) : null;
  3365. } catch (e) {
  3366. return null;
  3367. }
  3368. }
  3369. };
  3370. function parse (s) {
  3371. var d;
  3372. if (!s) {
  3373. return null;
  3374. }
  3375. if (s instanceof Date) {
  3376. return s.clone();
  3377. }
  3378. if (s.length >= 4 && s.charAt(0) !== "0" && s.charAt(0) !== "+"&& s.charAt(0) !== "-") { // ie: 2004 will pass, 0800 won't.
  3379. // Start with specific formats
  3380. d = $D.Parsing.ISO.parse(s) || $D.Parsing.Numeric.parse(s);
  3381. }
  3382. if (d instanceof Date && !isNaN(d.getTime())) {
  3383. return d;
  3384. } else {
  3385. // find ordinal dates (1st, 3rd, 8th, etc and remove them as they cause parsing issues)
  3386. s = $D.Parsing.Normalizer.parse(parseUtils.removeOrds(s));
  3387. d = parseUtils.grammarParser(s);
  3388. if (d !== null) {
  3389. return d;
  3390. } else {
  3391. return parseUtils.nativeFallback(s);
  3392. }
  3393. }
  3394. }
  3395. if (!$D._parse) {
  3396. $D._parse = $D.parse;
  3397. }
  3398. $D.parse = parse;
  3399. Date.getParseFunction = function (fx) {
  3400. var fns = Date.Grammar.allformats(fx);
  3401. return function (s) {
  3402. var r = null;
  3403. for (var i = 0; i < fns.length; i++) {
  3404. try {
  3405. r = fns[i].call({}, s);
  3406. } catch (e) {
  3407. continue;
  3408. }
  3409. if (r[1].length === 0) {
  3410. return r[0];
  3411. }
  3412. }
  3413. return null;
  3414. };
  3415. };
  3416. /**
  3417. * Converts the specified string value into its JavaScript Date equivalent using the specified format {String} or formats {Array} and the CultureInfo specific format information.
  3418. * The format of the string value must match one of the supplied formats exactly.
  3419. *
  3420. * Example
  3421. <pre><code>
  3422. // 15-Oct-2004
  3423. var d1 = Date.parseExact("10/15/2004", "M/d/yyyy");
  3424. // 15-Oct-2004
  3425. var d1 = Date.parse("15-Oct-2004", "M-ddd-yyyy");
  3426. // 15-Oct-2004
  3427. var d1 = Date.parse("2004.10.15", "yyyy.MM.dd");
  3428. // Multiple formats
  3429. var d1 = Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]);
  3430. </code></pre>
  3431. *
  3432. * @param {String} The string value to convert into a Date object [Required].
  3433. * @param {Object} The expected format {String} or an array of expected formats {Array} of the date string [Required].
  3434. * @return {Date} A Date object or null if the string cannot be converted into a Date.
  3435. */
  3436. $D.parseExact = function (s, fx) {
  3437. return $D.getParseFunction(fx)(s);
  3438. };
  3439. }());
  3440. (function () {
  3441. var $D = Date,
  3442. $P = $D.prototype,
  3443. // $C = $D.CultureInfo, // not used atm
  3444. p = function (s, l) {
  3445. if (!l) {
  3446. l = 2;
  3447. }
  3448. return ("000" + s).slice(l * -1);
  3449. };
  3450. /**
  3451. * Converts a PHP format string to Java/.NET format string.
  3452. * A PHP format string can be used with ._format or .format.
  3453. * A Java/.NET format string can be used with .toString().
  3454. * The .parseExact function will only accept a Java/.NET format string
  3455. *
  3456. * Example
  3457. * var f1 = "%m/%d/%y"
  3458. * var f2 = Date.normalizeFormat(f1); // "MM/dd/yy"
  3459. *
  3460. * new Date().format(f1); // "04/13/08"
  3461. * new Date()._format(f1); // "04/13/08"
  3462. * new Date().toString(f2); // "04/13/08"
  3463. *
  3464. * var date = Date.parseExact("04/13/08", f2); // Sun Apr 13 2008
  3465. *
  3466. * @param {String} A PHP format string consisting of one or more format spcifiers.
  3467. * @return {String} The PHP format converted to a Java/.NET format string.
  3468. */
  3469. var normalizerSubstitutions = {
  3470. "d" : "dd",
  3471. "%d": "dd",
  3472. "D" : "ddd",
  3473. "%a": "ddd",
  3474. "j" : "dddd",
  3475. "l" : "dddd",
  3476. "%A": "dddd",
  3477. "S" : "S",
  3478. "F" : "MMMM",
  3479. "%B": "MMMM",
  3480. "m" : "MM",
  3481. "%m": "MM",
  3482. "M" : "MMM",
  3483. "%b": "MMM",
  3484. "%h": "MMM",
  3485. "n" : "M",
  3486. "Y" : "yyyy",
  3487. "%Y": "yyyy",
  3488. "y" : "yy",
  3489. "%y": "yy",
  3490. "g" : "h",
  3491. "%I": "h",
  3492. "G" : "H",
  3493. "h" : "hh",
  3494. "H" : "HH",
  3495. "%H": "HH",
  3496. "i" : "mm",
  3497. "%M": "mm",
  3498. "s" : "ss",
  3499. "%S": "ss",
  3500. "%r": "hh:mm tt",
  3501. "%R": "H:mm",
  3502. "%T": "H:mm:ss",
  3503. "%X": "t",
  3504. "%x": "d",
  3505. "%e": "d",
  3506. "%D": "MM/dd/yy",
  3507. "%n": "\\n",
  3508. "%t": "\\t",
  3509. "e" : "z",
  3510. "T" : "z",
  3511. "%z": "z",
  3512. "%Z": "z",
  3513. "Z" : "ZZ",
  3514. "N" : "u",
  3515. "w" : "u",
  3516. "%w": "u",
  3517. "W" : "W",
  3518. "%V": "W"
  3519. };
  3520. var normalizer = {
  3521. substitutes: function (m) {
  3522. return normalizerSubstitutions[m];
  3523. },
  3524. interpreted: function (m, x) {
  3525. var y;
  3526. switch (m) {
  3527. case "%u":
  3528. return x.getDay() + 1;
  3529. case "z":
  3530. return x.getOrdinalNumber();
  3531. case "%j":
  3532. return p(x.getOrdinalNumber(), 3);
  3533. case "%U":
  3534. var d1 = x.clone().set({month: 0, day: 1}).addDays(-1).moveToDayOfWeek(0),
  3535. d2 = x.clone().addDays(1).moveToDayOfWeek(0, -1);
  3536. return (d2 < d1) ? "00" : p((d2.getOrdinalNumber() - d1.getOrdinalNumber()) / 7 + 1);
  3537. case "%W":
  3538. return p(x.getWeek());
  3539. case "t":
  3540. return $D.getDaysInMonth(x.getFullYear(), x.getMonth());
  3541. case "o":
  3542. case "%G":
  3543. return x.setWeek(x.getISOWeek()).toString("yyyy");
  3544. case "%g":
  3545. return x._format("%G").slice(-2);
  3546. case "a":
  3547. case "%p":
  3548. return t("tt").toLowerCase();
  3549. case "A":
  3550. return t("tt").toUpperCase();
  3551. case "u":
  3552. return p(x.getMilliseconds(), 3);
  3553. case "I":
  3554. return (x.isDaylightSavingTime()) ? 1 : 0;
  3555. case "O":
  3556. return x.getUTCOffset();
  3557. case "P":
  3558. y = x.getUTCOffset();
  3559. return y.substring(0, y.length - 2) + ":" + y.substring(y.length - 2);
  3560. case "B":
  3561. var now = new Date();
  3562. return Math.floor(((now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds() + (now.getTimezoneOffset() + 60) * 60) / 86.4);
  3563. case "c":
  3564. return x.toISOString().replace(/\"/g, "");
  3565. case "U":
  3566. return $D.strtotime("now");
  3567. case "%c":
  3568. return t("d") + " " + t("t");
  3569. case "%C":
  3570. return Math.floor(x.getFullYear() / 100 + 1);
  3571. }
  3572. },
  3573. shouldOverrideDefaults: function (m) {
  3574. switch (m) {
  3575. case "%e":
  3576. return true;
  3577. default:
  3578. return false;
  3579. }
  3580. },
  3581. parse: function (m, context) {
  3582. var formatString, c = context || new Date();
  3583. formatString = normalizer.substitutes(m);
  3584. if (formatString) {
  3585. return formatString;
  3586. }
  3587. formatString = normalizer.interpreted(m, c);
  3588. if (formatString) {
  3589. return formatString;
  3590. } else {
  3591. return m;
  3592. }
  3593. }
  3594. };
  3595. $D.normalizeFormat = function (format, context) {
  3596. return format.replace(/(%|\\)?.|%%/g, function(t){
  3597. return normalizer.parse(t, context);
  3598. });
  3599. };
  3600. /**
  3601. * Format a local Unix timestamp according to locale settings
  3602. *
  3603. * Example:
  3604. * Date.strftime("%m/%d/%y", new Date()); // "04/13/08"
  3605. * Date.strftime("c", "2008-04-13T17:52:03Z"); // "04/13/08"
  3606. *
  3607. * @param {String} A format string consisting of one or more format spcifiers [Optional].
  3608. * @param {Number|String} The number representing the number of seconds that have elapsed since January 1, 1970 (local time).
  3609. * @return {String} A string representation of the current Date object.
  3610. */
  3611. $D.strftime = function (format, time) {
  3612. var d = Date.parse(time);
  3613. return d._format(format);
  3614. };
  3615. /**
  3616. * Parse any textual datetime description into a Unix timestamp.
  3617. * A Unix timestamp is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT).
  3618. *
  3619. * Example:
  3620. * Date.strtotime("04/13/08"); // 1208044800
  3621. * Date.strtotime("1970-01-01T00:00:00Z"); // 0
  3622. *
  3623. * @param {String} A format string consisting of one or more format spcifiers [Optional].
  3624. * @param {Object} A string or date object.
  3625. * @return {String} A string representation of the current Date object.
  3626. */
  3627. $D.strtotime = function (time) {
  3628. var d = $D.parse(time);
  3629. return Math.round($D.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()) / 1000);
  3630. };
  3631. /**
  3632. * Converts the value of the current Date object to its equivalent string representation using a PHP/Unix style of date format specifiers.
  3633. * Format Specifiers
  3634. * Format Description Example
  3635. * ------ --------------------------------------------------------------------------- -----------------------
  3636. * %a abbreviated weekday name according to the current localed "Mon" through "Sun"
  3637. * %A full weekday name according to the current localed "Sunday" through "Saturday"
  3638. * %b abbreviated month name according to the current localed "Jan" through "Dec"
  3639. * %B full month name according to the current locale "January" through "December"
  3640. * %c preferred date and time representation for the current locale "4/13/2008 12:33 PM"
  3641. * %C century number (the year divided by 100 and truncated to an integer) "00" to "99"
  3642. * %d day of the month as a decimal number "01" to "31"
  3643. * %D same as %m/%d/%y "04/13/08"
  3644. * %e day of the month as a decimal number, a single digit is preceded by a space "1" to "31"
  3645. * %g like %G, but without the century "08"
  3646. * %G The 4-digit year corresponding to the ISO week number (see %V). "2008"
  3647. * This has the same format and value as %Y, except that if the ISO week number
  3648. * belongs to the previous or next year, that year is used instead.
  3649. * %h same as %b "Jan" through "Dec"
  3650. * %H hour as a decimal number using a 24-hour clock. "00" to "23"
  3651. * %I hour as a decimal number using a 12-hour clock. "01" to "12"
  3652. * %j day of the year as a decimal number. "001" to "366"
  3653. * %m month as a decimal number. "01" to "12"
  3654. * %M minute as a decimal number. "00" to "59"
  3655. * %n newline character "\n"
  3656. * %p either "am" or "pm" according to the given time value, or the "am" or "pm"
  3657. * corresponding strings for the current locale.
  3658. * %r time in a.m. and p.m. notation "8:44 PM"
  3659. * %R time in 24 hour notation "20:44"
  3660. * %S second as a decimal number "00" to "59"
  3661. * %t tab character "\t"
  3662. * %T current time, equal to %H:%M:%S "12:49:11"
  3663. * %u weekday as a decimal number ["1", "7"], with "1" representing Monday "1" to "7"
  3664. * %U week number of the current year as a decimal number, starting with the "0" to ("52" or "53")
  3665. * first Sunday as the first day of the first week
  3666. * %V The ISO 8601:1988 week number of the current year as a decimal number, "00" to ("52" or "53")
  3667. * range 01 to 53, where week 1 is the first week that has at least 4 days
  3668. * in the current year, and with Monday as the first day of the week.
  3669. * (Use %G or %g for the year component that corresponds to the week number
  3670. * for the specified timestamp.)
  3671. * %W week number of the current year as a decimal number, starting with the "00" to ("52" or "53")
  3672. * first Monday as the first day of the first week
  3673. * %w day of the week as a decimal, Sunday being "0" "0" to "6"
  3674. * %x preferred date representation for the current locale without the time "4/13/2008"
  3675. * %X preferred time representation for the current locale without the date "12:53:05"
  3676. * %y year as a decimal number without a century "00" "99"
  3677. * %Y year as a decimal number including the century "2008"
  3678. * %Z time zone or name or abbreviation "UTC", "EST", "PST"
  3679. * %z same as %Z
  3680. * %% a literal "%" characters "%"
  3681. * d Day of the month, 2 digits with leading zeros "01" to "31"
  3682. * D A textual representation of a day, three letters "Mon" through "Sun"
  3683. * j Day of the month without leading zeros "1" to "31"
  3684. * l A full textual representation of the day of the week (lowercase "L") "Sunday" through "Saturday"
  3685. * N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) "1" (for Monday) through "7" (for Sunday)
  3686. * S English ordinal suffix for the day of the month, 2 characters "st", "nd", "rd" or "th". Works well with j
  3687. * w Numeric representation of the day of the week "0" (for Sunday) through "6" (for Saturday)
  3688. * z The day of the year (starting from "0") "0" through "365"
  3689. * W ISO-8601 week number of year, weeks starting on Monday "00" to ("52" or "53")
  3690. * F A full textual representation of a month, such as January or March "January" through "December"
  3691. * m Numeric representation of a month, with leading zeros "01" through "12"
  3692. * M A short textual representation of a month, three letters "Jan" through "Dec"
  3693. * n Numeric representation of a month, without leading zeros "1" through "12"
  3694. * t Number of days in the given month "28" through "31"
  3695. * L Whether it's a leap year "1" if it is a leap year, "0" otherwise
  3696. * o ISO-8601 year number. This has the same value as Y, except that if the "2008"
  3697. * ISO week number (W) belongs to the previous or next year, that year
  3698. * is used instead.
  3699. * Y A full numeric representation of a year, 4 digits "2008"
  3700. * y A two digit representation of a year "08"
  3701. * a Lowercase Ante meridiem and Post meridiem "am" or "pm"
  3702. * A Uppercase Ante meridiem and Post meridiem "AM" or "PM"
  3703. * B Swatch Internet time "000" through "999"
  3704. * g 12-hour format of an hour without leading zeros "1" through "12"
  3705. * G 24-hour format of an hour without leading zeros "0" through "23"
  3706. * h 12-hour format of an hour with leading zeros "01" through "12"
  3707. * H 24-hour format of an hour with leading zeros "00" through "23"
  3708. * i Minutes with leading zeros "00" to "59"
  3709. * s Seconds, with leading zeros "00" through "59"
  3710. * u Milliseconds "54321"
  3711. * e Timezone identifier "UTC", "EST", "PST"
  3712. * I Whether or not the date is in daylight saving time (uppercase i) "1" if Daylight Saving Time, "0" otherwise
  3713. * O Difference to Greenwich time (GMT) in hours "+0200", "-0600"
  3714. * P Difference to Greenwich time (GMT) with colon between hours and minutes "+02:00", "-06:00"
  3715. * T Timezone abbreviation "UTC", "EST", "PST"
  3716. * Z Timezone offset in seconds. The offset for timezones west of UTC is "-43200" through "50400"
  3717. * always negative, and for those east of UTC is always positive.
  3718. * c ISO 8601 date "2004-02-12T15:19:21+00:00"
  3719. * r RFC 2822 formatted date "Thu, 21 Dec 2000 16:01:07 +0200"
  3720. * U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) "0"
  3721. * @param {String} A format string consisting of one or more format spcifiers [Optional].
  3722. * @return {String} A string representation of the current Date object.
  3723. */
  3724. var formatReplace = function (context) {
  3725. return function (m) {
  3726. var formatString, override = false;
  3727. if (m.charAt(0) === "\\" || m.substring(0, 2) === "%%") {
  3728. return m.replace("\\", "").replace("%%", "%");
  3729. }
  3730. override = normalizer.shouldOverrideDefaults(m);
  3731. formatString = $D.normalizeFormat(m, context);
  3732. if (formatString) {
  3733. return context.toString(formatString, override);
  3734. }
  3735. };
  3736. };
  3737. $P._format = function (format) {
  3738. var formatter = formatReplace(this);
  3739. if (!format) {
  3740. return this._toString();
  3741. } else {
  3742. return format.replace(/(%|\\)?.|%%/g, formatter);
  3743. }
  3744. };
  3745. if (!$P.format) {
  3746. $P.format = $P._format;
  3747. }
  3748. }());
  3749. (function () {
  3750. "use strict";
  3751. var gFn = function (attr) {
  3752. return function () {
  3753. return this[attr];
  3754. };
  3755. };
  3756. var sFn = function (attr) {
  3757. return function (val) {
  3758. this[attr] = val;
  3759. return this;
  3760. };
  3761. };
  3762. var attrs = ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"];
  3763. var addSetFuncs = function (context, attrs) {
  3764. for (var i = 0; i < attrs.length ; i++) {
  3765. var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1);
  3766. context.prototype[$a] = 0;
  3767. context.prototype["get" + $b] = gFn($a);
  3768. context.prototype["set" + $b] = sFn($a);
  3769. }
  3770. };
  3771. /**
  3772. * new TimeSpan(milliseconds);
  3773. * new TimeSpan(days, hours, minutes, seconds);
  3774. * new TimeSpan(days, hours, minutes, seconds, milliseconds);
  3775. */
  3776. var TimeSpan = function (days, hours, minutes, seconds, milliseconds) {
  3777. if (arguments.length === 1 && typeof days === "number") {
  3778. var orient = (days < 0) ? -1 : +1;
  3779. var millsLeft = Math.abs(days);
  3780. this.setDays(Math.floor(millsLeft / 86400000) * orient);
  3781. millsLeft = millsLeft % 86400000;
  3782. this.setHours(Math.floor(millsLeft / 3600000) * orient);
  3783. millsLeft = millsLeft % 3600000;
  3784. this.setMinutes(Math.floor(millsLeft / 60000) * orient);
  3785. millsLeft = millsLeft % 60000;
  3786. this.setSeconds(Math.floor(millsLeft / 1000) * orient);
  3787. millsLeft = millsLeft % 1000;
  3788. this.setMilliseconds(millsLeft * orient);
  3789. } else {
  3790. this.set(days, hours, minutes, seconds, milliseconds);
  3791. }
  3792. this.getTotalMilliseconds = function () {
  3793. return (this.getDays() * 86400000) +
  3794. (this.getHours() * 3600000) +
  3795. (this.getMinutes() * 60000) +
  3796. (this.getSeconds() * 1000);
  3797. };
  3798. this.compareTo = function (time) {
  3799. var t1 = new Date(1970, 1, 1, this.getHours(), this.getMinutes(), this.getSeconds()), t2;
  3800. if (time === null) {
  3801. t2 = new Date(1970, 1, 1, 0, 0, 0);
  3802. }
  3803. else {
  3804. t2 = new Date(1970, 1, 1, time.getHours(), time.getMinutes(), time.getSeconds());
  3805. }
  3806. return (t1 < t2) ? -1 : (t1 > t2) ? 1 : 0;
  3807. };
  3808. this.equals = function (time) {
  3809. return (this.compareTo(time) === 0);
  3810. };
  3811. this.add = function (time) {
  3812. return (time === null) ? this : this.addSeconds(time.getTotalMilliseconds() / 1000);
  3813. };
  3814. this.subtract = function (time) {
  3815. return (time === null) ? this : this.addSeconds(-time.getTotalMilliseconds() / 1000);
  3816. };
  3817. this.addDays = function (n) {
  3818. return new TimeSpan(this.getTotalMilliseconds() + (n * 86400000));
  3819. };
  3820. this.addHours = function (n) {
  3821. return new TimeSpan(this.getTotalMilliseconds() + (n * 3600000));
  3822. };
  3823. this.addMinutes = function (n) {
  3824. return new TimeSpan(this.getTotalMilliseconds() + (n * 60000));
  3825. };
  3826. this.addSeconds = function (n) {
  3827. return new TimeSpan(this.getTotalMilliseconds() + (n * 1000));
  3828. };
  3829. this.addMilliseconds = function (n) {
  3830. return new TimeSpan(this.getTotalMilliseconds() + n);
  3831. };
  3832. this.get12HourHour = function () {
  3833. return (this.getHours() > 12) ? this.getHours() - 12 : (this.getHours() === 0) ? 12 : this.getHours();
  3834. };
  3835. this.getDesignator = function () {
  3836. return (this.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator;
  3837. };
  3838. this.toString = function (format) {
  3839. this._toString = function () {
  3840. if (this.getDays() !== null && this.getDays() > 0) {
  3841. return this.getDays() + "." + this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds());
  3842. } else {
  3843. return this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds());
  3844. }
  3845. };
  3846. this.p = function (s) {
  3847. return (s.toString().length < 2) ? "0" + s : s;
  3848. };
  3849. var me = this;
  3850. return format ? format.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g,
  3851. function (format) {
  3852. switch (format) {
  3853. case "d":
  3854. return me.getDays();
  3855. case "dd":
  3856. return me.p(me.getDays());
  3857. case "H":
  3858. return me.getHours();
  3859. case "HH":
  3860. return me.p(me.getHours());
  3861. case "h":
  3862. return me.get12HourHour();
  3863. case "hh":
  3864. return me.p(me.get12HourHour());
  3865. case "m":
  3866. return me.getMinutes();
  3867. case "mm":
  3868. return me.p(me.getMinutes());
  3869. case "s":
  3870. return me.getSeconds();
  3871. case "ss":
  3872. return me.p(me.getSeconds());
  3873. case "t":
  3874. return ((me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator).substring(0, 1);
  3875. case "tt":
  3876. return (me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator;
  3877. }
  3878. }
  3879. ) : this._toString();
  3880. };
  3881. return this;
  3882. };
  3883. addSetFuncs(TimeSpan, attrs.slice(2));
  3884. TimeSpan.prototype.set = function (days, hours, minutes, seconds, milliseconds){
  3885. this.setDays(days || this.getDays());
  3886. this.setHours(hours || this.getHours());
  3887. this.setMinutes(minutes || this.getMinutes());
  3888. this.setSeconds(seconds || this.getSeconds());
  3889. this.setMilliseconds(milliseconds || this.getMilliseconds());
  3890. };
  3891. /**
  3892. * Gets the time of day for this date instances.
  3893. * @return {TimeSpan} TimeSpan
  3894. */
  3895. Date.prototype.getTimeOfDay = function () {
  3896. return new TimeSpan(0, this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
  3897. };
  3898. Date.TimeSpan = TimeSpan;
  3899. if (typeof window !== "undefined" ) {
  3900. // keeping API compatible for v1.x
  3901. window.TimeSpan = TimeSpan;
  3902. }
  3903. }());
  3904. (function () {
  3905. "use strict";
  3906. var attrs = ["years", "months", "days", "hours", "minutes", "seconds", "milliseconds"];
  3907. var gFn = function (attr) {
  3908. return function () {
  3909. return this[attr];
  3910. };
  3911. };
  3912. var sFn = function (attr) {
  3913. return function (val) {
  3914. this[attr] = val;
  3915. return this;
  3916. };
  3917. };
  3918. var addSetFuncs = function (context, attrs) {
  3919. for (var i = 0; i < attrs.length ; i++) {
  3920. var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1);
  3921. context.prototype[$a] = 0;
  3922. context.prototype["get" + $b] = gFn($a);
  3923. context.prototype["set" + $b] = sFn($a);
  3924. }
  3925. };
  3926. var setMonthsAndYears = function (orient, d1, d2, context) {
  3927. function inc() {
  3928. d1.addMonths(-orient);
  3929. context.months++;
  3930. if (context.months === 12) {
  3931. context.years++;
  3932. context.months = 0;
  3933. }
  3934. }
  3935. if (orient === +1) {
  3936. while (d1 > d2) {
  3937. inc();
  3938. }
  3939. } else {
  3940. while (d1 < d2) {
  3941. inc();
  3942. }
  3943. }
  3944. context.months--;
  3945. context.months *= orient;
  3946. context.years *= orient;
  3947. };
  3948. var adjustForDST = function(orient, startDate, endDate) {
  3949. var hasDSTMismatch = (false === (startDate.isDaylightSavingTime() === endDate.isDaylightSavingTime()));
  3950. if (hasDSTMismatch && orient === 1) {
  3951. startDate.addHours(-1);
  3952. } else if (hasDSTMismatch) {
  3953. startDate.addHours(1);
  3954. }
  3955. };
  3956. /**
  3957. * TimePeriod(startDate, endDate);
  3958. * TimePeriod(years, months, days, hours, minutes, seconds, milliseconds);
  3959. */
  3960. var TimePeriod = function (years, months, days, hours, minutes, seconds, milliseconds) {
  3961. if (arguments.length === 7) {
  3962. this.set(years, months, days, hours, minutes, seconds, milliseconds);
  3963. } else if (arguments.length === 2 && arguments[0] instanceof Date && arguments[1] instanceof Date) {
  3964. var startDate = arguments[0].clone();
  3965. var endDate = arguments[1].clone();
  3966. var orient = (startDate > endDate) ? +1 : -1;
  3967. this.dates = {
  3968. start: arguments[0].clone(),
  3969. end: arguments[1].clone()
  3970. };
  3971. setMonthsAndYears(orient, startDate, endDate, this);
  3972. adjustForDST(orient, startDate, endDate);
  3973. // // TODO - adjust for DST
  3974. var diff = endDate - startDate;
  3975. if (diff !== 0) {
  3976. var ts = new TimeSpan(diff);
  3977. this.set(this.years, this.months, ts.getDays(), ts.getHours(), ts.getMinutes(), ts.getSeconds(), ts.getMilliseconds());
  3978. }
  3979. }
  3980. return this;
  3981. };
  3982. // create all the set functions.
  3983. addSetFuncs(TimePeriod, attrs);
  3984. TimePeriod.prototype.set = function (years, months, days, hours, minutes, seconds, milliseconds){
  3985. this.setYears(years || this.getYears());
  3986. this.setMonths(months || this.getMonths());
  3987. this.setDays(days || this.getDays());
  3988. this.setHours(hours || this.getHours());
  3989. this.setMinutes(minutes || this.getMinutes());
  3990. this.setSeconds(seconds || this.getSeconds());
  3991. this.setMilliseconds(milliseconds || this.getMilliseconds());
  3992. };
  3993. Date.TimePeriod = TimePeriod;
  3994. if (typeof window !== "undefined") {
  3995. // keeping API compatible for v1.x
  3996. window.TimePeriod = TimePeriod;
  3997. }
  3998. }());