datetime.js 93 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556
  1. import Duration from "./duration.js";
  2. import Interval from "./interval.js";
  3. import Settings from "./settings.js";
  4. import Info from "./info.js";
  5. import Formatter from "./impl/formatter.js";
  6. import FixedOffsetZone from "./zones/fixedOffsetZone.js";
  7. import Locale from "./impl/locale.js";
  8. import {
  9. isUndefined,
  10. maybeArray,
  11. isDate,
  12. isNumber,
  13. bestBy,
  14. daysInMonth,
  15. daysInYear,
  16. isLeapYear,
  17. weeksInWeekYear,
  18. normalizeObject,
  19. roundTo,
  20. objToLocalTS,
  21. padStart,
  22. } from "./impl/util.js";
  23. import { normalizeZone } from "./impl/zoneUtil.js";
  24. import diff from "./impl/diff.js";
  25. import { parseRFC2822Date, parseISODate, parseHTTPDate, parseSQL } from "./impl/regexParser.js";
  26. import {
  27. parseFromTokens,
  28. explainFromTokens,
  29. formatOptsToTokens,
  30. expandMacroTokens,
  31. TokenParser,
  32. } from "./impl/tokenParser.js";
  33. import {
  34. gregorianToWeek,
  35. weekToGregorian,
  36. gregorianToOrdinal,
  37. ordinalToGregorian,
  38. hasInvalidGregorianData,
  39. hasInvalidWeekData,
  40. hasInvalidOrdinalData,
  41. hasInvalidTimeData,
  42. usesLocalWeekValues,
  43. isoWeekdayToLocal,
  44. } from "./impl/conversions.js";
  45. import * as Formats from "./impl/formats.js";
  46. import {
  47. InvalidArgumentError,
  48. ConflictingSpecificationError,
  49. InvalidUnitError,
  50. InvalidDateTimeError,
  51. } from "./errors.js";
  52. import Invalid from "./impl/invalid.js";
  53. const INVALID = "Invalid DateTime";
  54. const MAX_DATE = 8.64e15;
  55. function unsupportedZone(zone) {
  56. return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`);
  57. }
  58. // we cache week data on the DT object and this intermediates the cache
  59. /**
  60. * @param {DateTime} dt
  61. */
  62. function possiblyCachedWeekData(dt) {
  63. if (dt.weekData === null) {
  64. dt.weekData = gregorianToWeek(dt.c);
  65. }
  66. return dt.weekData;
  67. }
  68. /**
  69. * @param {DateTime} dt
  70. */
  71. function possiblyCachedLocalWeekData(dt) {
  72. if (dt.localWeekData === null) {
  73. dt.localWeekData = gregorianToWeek(
  74. dt.c,
  75. dt.loc.getMinDaysInFirstWeek(),
  76. dt.loc.getStartOfWeek()
  77. );
  78. }
  79. return dt.localWeekData;
  80. }
  81. // clone really means, "make a new object with these modifications". all "setters" really use this
  82. // to create a new object while only changing some of the properties
  83. function clone(inst, alts) {
  84. const current = {
  85. ts: inst.ts,
  86. zone: inst.zone,
  87. c: inst.c,
  88. o: inst.o,
  89. loc: inst.loc,
  90. invalid: inst.invalid,
  91. };
  92. return new DateTime({ ...current, ...alts, old: current });
  93. }
  94. // find the right offset a given local time. The o input is our guess, which determines which
  95. // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST)
  96. function fixOffset(localTS, o, tz) {
  97. // Our UTC time is just a guess because our offset is just a guess
  98. let utcGuess = localTS - o * 60 * 1000;
  99. // Test whether the zone matches the offset for this ts
  100. const o2 = tz.offset(utcGuess);
  101. // If so, offset didn't change and we're done
  102. if (o === o2) {
  103. return [utcGuess, o];
  104. }
  105. // If not, change the ts by the difference in the offset
  106. utcGuess -= (o2 - o) * 60 * 1000;
  107. // If that gives us the local time we want, we're done
  108. const o3 = tz.offset(utcGuess);
  109. if (o2 === o3) {
  110. return [utcGuess, o2];
  111. }
  112. // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time
  113. return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)];
  114. }
  115. // convert an epoch timestamp into a calendar object with the given offset
  116. function tsToObj(ts, offset) {
  117. ts += offset * 60 * 1000;
  118. const d = new Date(ts);
  119. return {
  120. year: d.getUTCFullYear(),
  121. month: d.getUTCMonth() + 1,
  122. day: d.getUTCDate(),
  123. hour: d.getUTCHours(),
  124. minute: d.getUTCMinutes(),
  125. second: d.getUTCSeconds(),
  126. millisecond: d.getUTCMilliseconds(),
  127. };
  128. }
  129. // convert a calendar object to a epoch timestamp
  130. function objToTS(obj, offset, zone) {
  131. return fixOffset(objToLocalTS(obj), offset, zone);
  132. }
  133. // create a new DT instance by adding a duration, adjusting for DSTs
  134. function adjustTime(inst, dur) {
  135. const oPre = inst.o,
  136. year = inst.c.year + Math.trunc(dur.years),
  137. month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3,
  138. c = {
  139. ...inst.c,
  140. year,
  141. month,
  142. day:
  143. Math.min(inst.c.day, daysInMonth(year, month)) +
  144. Math.trunc(dur.days) +
  145. Math.trunc(dur.weeks) * 7,
  146. },
  147. millisToAdd = Duration.fromObject({
  148. years: dur.years - Math.trunc(dur.years),
  149. quarters: dur.quarters - Math.trunc(dur.quarters),
  150. months: dur.months - Math.trunc(dur.months),
  151. weeks: dur.weeks - Math.trunc(dur.weeks),
  152. days: dur.days - Math.trunc(dur.days),
  153. hours: dur.hours,
  154. minutes: dur.minutes,
  155. seconds: dur.seconds,
  156. milliseconds: dur.milliseconds,
  157. }).as("milliseconds"),
  158. localTS = objToLocalTS(c);
  159. let [ts, o] = fixOffset(localTS, oPre, inst.zone);
  160. if (millisToAdd !== 0) {
  161. ts += millisToAdd;
  162. // that could have changed the offset by going over a DST, but we want to keep the ts the same
  163. o = inst.zone.offset(ts);
  164. }
  165. return { ts, o };
  166. }
  167. // helper useful in turning the results of parsing into real dates
  168. // by handling the zone options
  169. function parseDataToDateTime(parsed, parsedZone, opts, format, text, specificOffset) {
  170. const { setZone, zone } = opts;
  171. if ((parsed && Object.keys(parsed).length !== 0) || parsedZone) {
  172. const interpretationZone = parsedZone || zone,
  173. inst = DateTime.fromObject(parsed, {
  174. ...opts,
  175. zone: interpretationZone,
  176. specificOffset,
  177. });
  178. return setZone ? inst : inst.setZone(zone);
  179. } else {
  180. return DateTime.invalid(
  181. new Invalid("unparsable", `the input "${text}" can't be parsed as ${format}`)
  182. );
  183. }
  184. }
  185. // if you want to output a technical format (e.g. RFC 2822), this helper
  186. // helps handle the details
  187. function toTechFormat(dt, format, allowZ = true) {
  188. return dt.isValid
  189. ? Formatter.create(Locale.create("en-US"), {
  190. allowZ,
  191. forceSimple: true,
  192. }).formatDateTimeFromString(dt, format)
  193. : null;
  194. }
  195. function toISODate(o, extended) {
  196. const longFormat = o.c.year > 9999 || o.c.year < 0;
  197. let c = "";
  198. if (longFormat && o.c.year >= 0) c += "+";
  199. c += padStart(o.c.year, longFormat ? 6 : 4);
  200. if (extended) {
  201. c += "-";
  202. c += padStart(o.c.month);
  203. c += "-";
  204. c += padStart(o.c.day);
  205. } else {
  206. c += padStart(o.c.month);
  207. c += padStart(o.c.day);
  208. }
  209. return c;
  210. }
  211. function toISOTime(
  212. o,
  213. extended,
  214. suppressSeconds,
  215. suppressMilliseconds,
  216. includeOffset,
  217. extendedZone
  218. ) {
  219. let c = padStart(o.c.hour);
  220. if (extended) {
  221. c += ":";
  222. c += padStart(o.c.minute);
  223. if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {
  224. c += ":";
  225. }
  226. } else {
  227. c += padStart(o.c.minute);
  228. }
  229. if (o.c.millisecond !== 0 || o.c.second !== 0 || !suppressSeconds) {
  230. c += padStart(o.c.second);
  231. if (o.c.millisecond !== 0 || !suppressMilliseconds) {
  232. c += ".";
  233. c += padStart(o.c.millisecond, 3);
  234. }
  235. }
  236. if (includeOffset) {
  237. if (o.isOffsetFixed && o.offset === 0 && !extendedZone) {
  238. c += "Z";
  239. } else if (o.o < 0) {
  240. c += "-";
  241. c += padStart(Math.trunc(-o.o / 60));
  242. c += ":";
  243. c += padStart(Math.trunc(-o.o % 60));
  244. } else {
  245. c += "+";
  246. c += padStart(Math.trunc(o.o / 60));
  247. c += ":";
  248. c += padStart(Math.trunc(o.o % 60));
  249. }
  250. }
  251. if (extendedZone) {
  252. c += "[" + o.zone.ianaName + "]";
  253. }
  254. return c;
  255. }
  256. // defaults for unspecified units in the supported calendars
  257. const defaultUnitValues = {
  258. month: 1,
  259. day: 1,
  260. hour: 0,
  261. minute: 0,
  262. second: 0,
  263. millisecond: 0,
  264. },
  265. defaultWeekUnitValues = {
  266. weekNumber: 1,
  267. weekday: 1,
  268. hour: 0,
  269. minute: 0,
  270. second: 0,
  271. millisecond: 0,
  272. },
  273. defaultOrdinalUnitValues = {
  274. ordinal: 1,
  275. hour: 0,
  276. minute: 0,
  277. second: 0,
  278. millisecond: 0,
  279. };
  280. // Units in the supported calendars, sorted by bigness
  281. const orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"],
  282. orderedWeekUnits = [
  283. "weekYear",
  284. "weekNumber",
  285. "weekday",
  286. "hour",
  287. "minute",
  288. "second",
  289. "millisecond",
  290. ],
  291. orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"];
  292. // standardize case and plurality in units
  293. function normalizeUnit(unit) {
  294. const normalized = {
  295. year: "year",
  296. years: "year",
  297. month: "month",
  298. months: "month",
  299. day: "day",
  300. days: "day",
  301. hour: "hour",
  302. hours: "hour",
  303. minute: "minute",
  304. minutes: "minute",
  305. quarter: "quarter",
  306. quarters: "quarter",
  307. second: "second",
  308. seconds: "second",
  309. millisecond: "millisecond",
  310. milliseconds: "millisecond",
  311. weekday: "weekday",
  312. weekdays: "weekday",
  313. weeknumber: "weekNumber",
  314. weeksnumber: "weekNumber",
  315. weeknumbers: "weekNumber",
  316. weekyear: "weekYear",
  317. weekyears: "weekYear",
  318. ordinal: "ordinal",
  319. }[unit.toLowerCase()];
  320. if (!normalized) throw new InvalidUnitError(unit);
  321. return normalized;
  322. }
  323. function normalizeUnitWithLocalWeeks(unit) {
  324. switch (unit.toLowerCase()) {
  325. case "localweekday":
  326. case "localweekdays":
  327. return "localWeekday";
  328. case "localweeknumber":
  329. case "localweeknumbers":
  330. return "localWeekNumber";
  331. case "localweekyear":
  332. case "localweekyears":
  333. return "localWeekYear";
  334. default:
  335. return normalizeUnit(unit);
  336. }
  337. }
  338. // cache offsets for zones based on the current timestamp when this function is
  339. // first called. When we are handling a datetime from components like (year,
  340. // month, day, hour) in a time zone, we need a guess about what the timezone
  341. // offset is so that we can convert into a UTC timestamp. One way is to find the
  342. // offset of now in the zone. The actual date may have a different offset (for
  343. // example, if we handle a date in June while we're in December in a zone that
  344. // observes DST), but we can check and adjust that.
  345. //
  346. // When handling many dates, calculating the offset for now every time is
  347. // expensive. It's just a guess, so we can cache the offset to use even if we
  348. // are right on a time change boundary (we'll just correct in the other
  349. // direction). Using a timestamp from first read is a slight optimization for
  350. // handling dates close to the current date, since those dates will usually be
  351. // in the same offset (we could set the timestamp statically, instead). We use a
  352. // single timestamp for all zones to make things a bit more predictable.
  353. //
  354. // This is safe for quickDT (used by local() and utc()) because we don't fill in
  355. // higher-order units from tsNow (as we do in fromObject, this requires that
  356. // offset is calculated from tsNow).
  357. function guessOffsetForZone(zone) {
  358. if (!zoneOffsetGuessCache[zone]) {
  359. if (zoneOffsetTs === undefined) {
  360. zoneOffsetTs = Settings.now();
  361. }
  362. zoneOffsetGuessCache[zone] = zone.offset(zoneOffsetTs);
  363. }
  364. return zoneOffsetGuessCache[zone];
  365. }
  366. // this is a dumbed down version of fromObject() that runs about 60% faster
  367. // but doesn't do any validation, makes a bunch of assumptions about what units
  368. // are present, and so on.
  369. function quickDT(obj, opts) {
  370. const zone = normalizeZone(opts.zone, Settings.defaultZone);
  371. if (!zone.isValid) {
  372. return DateTime.invalid(unsupportedZone(zone));
  373. }
  374. const loc = Locale.fromObject(opts);
  375. let ts, o;
  376. // assume we have the higher-order units
  377. if (!isUndefined(obj.year)) {
  378. for (const u of orderedUnits) {
  379. if (isUndefined(obj[u])) {
  380. obj[u] = defaultUnitValues[u];
  381. }
  382. }
  383. const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj);
  384. if (invalid) {
  385. return DateTime.invalid(invalid);
  386. }
  387. const offsetProvis = guessOffsetForZone(zone);
  388. [ts, o] = objToTS(obj, offsetProvis, zone);
  389. } else {
  390. ts = Settings.now();
  391. }
  392. return new DateTime({ ts, zone, loc, o });
  393. }
  394. function diffRelative(start, end, opts) {
  395. const round = isUndefined(opts.round) ? true : opts.round,
  396. format = (c, unit) => {
  397. c = roundTo(c, round || opts.calendary ? 0 : 2, true);
  398. const formatter = end.loc.clone(opts).relFormatter(opts);
  399. return formatter.format(c, unit);
  400. },
  401. differ = (unit) => {
  402. if (opts.calendary) {
  403. if (!end.hasSame(start, unit)) {
  404. return end.startOf(unit).diff(start.startOf(unit), unit).get(unit);
  405. } else return 0;
  406. } else {
  407. return end.diff(start, unit).get(unit);
  408. }
  409. };
  410. if (opts.unit) {
  411. return format(differ(opts.unit), opts.unit);
  412. }
  413. for (const unit of opts.units) {
  414. const count = differ(unit);
  415. if (Math.abs(count) >= 1) {
  416. return format(count, unit);
  417. }
  418. }
  419. return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]);
  420. }
  421. function lastOpts(argList) {
  422. let opts = {},
  423. args;
  424. if (argList.length > 0 && typeof argList[argList.length - 1] === "object") {
  425. opts = argList[argList.length - 1];
  426. args = Array.from(argList).slice(0, argList.length - 1);
  427. } else {
  428. args = Array.from(argList);
  429. }
  430. return [opts, args];
  431. }
  432. /**
  433. * Timestamp to use for cached zone offset guesses (exposed for test)
  434. */
  435. let zoneOffsetTs;
  436. /**
  437. * Cache for zone offset guesses (exposed for test).
  438. *
  439. * This optimizes quickDT via guessOffsetForZone to avoid repeated calls of
  440. * zone.offset().
  441. */
  442. let zoneOffsetGuessCache = {};
  443. /**
  444. * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them.
  445. *
  446. * A DateTime comprises of:
  447. * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch.
  448. * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone).
  449. * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`.
  450. *
  451. * Here is a brief overview of the most commonly used functionality it provides:
  452. *
  453. * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link DateTime.local}, {@link DateTime.utc}, and (most flexibly) {@link DateTime.fromObject}. To create one from a standard string format, use {@link DateTime.fromISO}, {@link DateTime.fromHTTP}, and {@link DateTime.fromRFC2822}. To create one from a custom string format, use {@link DateTime.fromFormat}. To create one from a native JS date, use {@link DateTime.fromJSDate}.
  454. * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link DateTime#toObject}), use the {@link DateTime#year}, {@link DateTime#month},
  455. * {@link DateTime#day}, {@link DateTime#hour}, {@link DateTime#minute}, {@link DateTime#second}, {@link DateTime#millisecond} accessors.
  456. * * **Week calendar**: For ISO week calendar attributes, see the {@link DateTime#weekYear}, {@link DateTime#weekNumber}, and {@link DateTime#weekday} accessors.
  457. * * **Configuration** See the {@link DateTime#locale} and {@link DateTime#numberingSystem} accessors.
  458. * * **Transformation**: To transform the DateTime into other DateTimes, use {@link DateTime#set}, {@link DateTime#reconfigure}, {@link DateTime#setZone}, {@link DateTime#setLocale}, {@link DateTime.plus}, {@link DateTime#minus}, {@link DateTime#endOf}, {@link DateTime#startOf}, {@link DateTime#toUTC}, and {@link DateTime#toLocal}.
  459. * * **Output**: To convert the DateTime to other representations, use the {@link DateTime#toRelative}, {@link DateTime#toRelativeCalendar}, {@link DateTime#toJSON}, {@link DateTime#toISO}, {@link DateTime#toHTTP}, {@link DateTime#toObject}, {@link DateTime#toRFC2822}, {@link DateTime#toString}, {@link DateTime#toLocaleString}, {@link DateTime#toFormat}, {@link DateTime#toMillis} and {@link DateTime#toJSDate}.
  460. *
  461. * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation.
  462. */
  463. export default class DateTime {
  464. /**
  465. * @access private
  466. */
  467. constructor(config) {
  468. const zone = config.zone || Settings.defaultZone;
  469. let invalid =
  470. config.invalid ||
  471. (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) ||
  472. (!zone.isValid ? unsupportedZone(zone) : null);
  473. /**
  474. * @access private
  475. */
  476. this.ts = isUndefined(config.ts) ? Settings.now() : config.ts;
  477. let c = null,
  478. o = null;
  479. if (!invalid) {
  480. const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone);
  481. if (unchanged) {
  482. [c, o] = [config.old.c, config.old.o];
  483. } else {
  484. // If an offset has been passed and we have not been called from
  485. // clone(), we can trust it and avoid the offset calculation.
  486. const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts);
  487. c = tsToObj(this.ts, ot);
  488. invalid = Number.isNaN(c.year) ? new Invalid("invalid input") : null;
  489. c = invalid ? null : c;
  490. o = invalid ? null : ot;
  491. }
  492. }
  493. /**
  494. * @access private
  495. */
  496. this._zone = zone;
  497. /**
  498. * @access private
  499. */
  500. this.loc = config.loc || Locale.create();
  501. /**
  502. * @access private
  503. */
  504. this.invalid = invalid;
  505. /**
  506. * @access private
  507. */
  508. this.weekData = null;
  509. /**
  510. * @access private
  511. */
  512. this.localWeekData = null;
  513. /**
  514. * @access private
  515. */
  516. this.c = c;
  517. /**
  518. * @access private
  519. */
  520. this.o = o;
  521. /**
  522. * @access private
  523. */
  524. this.isLuxonDateTime = true;
  525. }
  526. // CONSTRUCT
  527. /**
  528. * Create a DateTime for the current instant, in the system's time zone.
  529. *
  530. * Use Settings to override these default values if needed.
  531. * @example DateTime.now().toISO() //~> now in the ISO format
  532. * @return {DateTime}
  533. */
  534. static now() {
  535. return new DateTime({});
  536. }
  537. /**
  538. * Create a local DateTime
  539. * @param {number} [year] - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used
  540. * @param {number} [month=1] - The month, 1-indexed
  541. * @param {number} [day=1] - The day of the month, 1-indexed
  542. * @param {number} [hour=0] - The hour of the day, in 24-hour time
  543. * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
  544. * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
  545. * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
  546. * @example DateTime.local() //~> now
  547. * @example DateTime.local({ zone: "America/New_York" }) //~> now, in US east coast time
  548. * @example DateTime.local(2017) //~> 2017-01-01T00:00:00
  549. * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00
  550. * @example DateTime.local(2017, 3, 12, { locale: "fr" }) //~> 2017-03-12T00:00:00, with a French locale
  551. * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00
  552. * @example DateTime.local(2017, 3, 12, 5, { zone: "utc" }) //~> 2017-03-12T05:00:00, in UTC
  553. * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00
  554. * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10
  555. * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765
  556. * @return {DateTime}
  557. */
  558. static local() {
  559. const [opts, args] = lastOpts(arguments),
  560. [year, month, day, hour, minute, second, millisecond] = args;
  561. return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  562. }
  563. /**
  564. * Create a DateTime in UTC
  565. * @param {number} [year] - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used
  566. * @param {number} [month=1] - The month, 1-indexed
  567. * @param {number} [day=1] - The day of the month
  568. * @param {number} [hour=0] - The hour of the day, in 24-hour time
  569. * @param {number} [minute=0] - The minute of the hour, meaning a number between 0 and 59
  570. * @param {number} [second=0] - The second of the minute, meaning a number between 0 and 59
  571. * @param {number} [millisecond=0] - The millisecond of the second, meaning a number between 0 and 999
  572. * @param {Object} options - configuration options for the DateTime
  573. * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
  574. * @param {string} [options.outputCalendar] - the output calendar to set on the resulting DateTime instance
  575. * @param {string} [options.numberingSystem] - the numbering system to set on the resulting DateTime instance
  576. * @param {string} [options.weekSettings] - the week settings to set on the resulting DateTime instance
  577. * @example DateTime.utc() //~> now
  578. * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z
  579. * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z
  580. * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z
  581. * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z
  582. * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z
  583. * @example DateTime.utc(2017, 3, 12, 5, 45, { locale: "fr" }) //~> 2017-03-12T05:45:00Z with a French locale
  584. * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z
  585. * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765, { locale: "fr" }) //~> 2017-03-12T05:45:10.765Z with a French locale
  586. * @return {DateTime}
  587. */
  588. static utc() {
  589. const [opts, args] = lastOpts(arguments),
  590. [year, month, day, hour, minute, second, millisecond] = args;
  591. opts.zone = FixedOffsetZone.utcInstance;
  592. return quickDT({ year, month, day, hour, minute, second, millisecond }, opts);
  593. }
  594. /**
  595. * Create a DateTime from a JavaScript Date object. Uses the default zone.
  596. * @param {Date} date - a JavaScript Date object
  597. * @param {Object} options - configuration options for the DateTime
  598. * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
  599. * @return {DateTime}
  600. */
  601. static fromJSDate(date, options = {}) {
  602. const ts = isDate(date) ? date.valueOf() : NaN;
  603. if (Number.isNaN(ts)) {
  604. return DateTime.invalid("invalid input");
  605. }
  606. const zoneToUse = normalizeZone(options.zone, Settings.defaultZone);
  607. if (!zoneToUse.isValid) {
  608. return DateTime.invalid(unsupportedZone(zoneToUse));
  609. }
  610. return new DateTime({
  611. ts: ts,
  612. zone: zoneToUse,
  613. loc: Locale.fromObject(options),
  614. });
  615. }
  616. /**
  617. * Create a DateTime from a number of milliseconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
  618. * @param {number} milliseconds - a number of milliseconds since 1970 UTC
  619. * @param {Object} options - configuration options for the DateTime
  620. * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
  621. * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
  622. * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
  623. * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
  624. * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
  625. * @return {DateTime}
  626. */
  627. static fromMillis(milliseconds, options = {}) {
  628. if (!isNumber(milliseconds)) {
  629. throw new InvalidArgumentError(
  630. `fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`
  631. );
  632. } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) {
  633. // this isn't perfect because we can still end up out of range because of additional shifting, but it's a start
  634. return DateTime.invalid("Timestamp out of range");
  635. } else {
  636. return new DateTime({
  637. ts: milliseconds,
  638. zone: normalizeZone(options.zone, Settings.defaultZone),
  639. loc: Locale.fromObject(options),
  640. });
  641. }
  642. }
  643. /**
  644. * Create a DateTime from a number of seconds since the epoch (meaning since 1 January 1970 00:00:00 UTC). Uses the default zone.
  645. * @param {number} seconds - a number of seconds since 1970 UTC
  646. * @param {Object} options - configuration options for the DateTime
  647. * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into
  648. * @param {string} [options.locale] - a locale to set on the resulting DateTime instance
  649. * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance
  650. * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance
  651. * @param {string} options.weekSettings - the week settings to set on the resulting DateTime instance
  652. * @return {DateTime}
  653. */
  654. static fromSeconds(seconds, options = {}) {
  655. if (!isNumber(seconds)) {
  656. throw new InvalidArgumentError("fromSeconds requires a numerical input");
  657. } else {
  658. return new DateTime({
  659. ts: seconds * 1000,
  660. zone: normalizeZone(options.zone, Settings.defaultZone),
  661. loc: Locale.fromObject(options),
  662. });
  663. }
  664. }
  665. /**
  666. * Create a DateTime from a JavaScript object with keys like 'year' and 'hour' with reasonable defaults.
  667. * @param {Object} obj - the object to create the DateTime from
  668. * @param {number} obj.year - a year, such as 1987
  669. * @param {number} obj.month - a month, 1-12
  670. * @param {number} obj.day - a day of the month, 1-31, depending on the month
  671. * @param {number} obj.ordinal - day of the year, 1-365 or 366
  672. * @param {number} obj.weekYear - an ISO week year
  673. * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year
  674. * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday
  675. * @param {number} obj.localWeekYear - a week year, according to the locale
  676. * @param {number} obj.localWeekNumber - a week number, between 1 and 52 or 53, depending on the year, according to the locale
  677. * @param {number} obj.localWeekday - a weekday, 1-7, where 1 is the first and 7 is the last day of the week, according to the locale
  678. * @param {number} obj.hour - hour of the day, 0-23
  679. * @param {number} obj.minute - minute of the hour, 0-59
  680. * @param {number} obj.second - second of the minute, 0-59
  681. * @param {number} obj.millisecond - millisecond of the second, 0-999
  682. * @param {Object} opts - options for creating this DateTime
  683. * @param {string|Zone} [opts.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone()
  684. * @param {string} [opts.locale='system\'s locale'] - a locale to set on the resulting DateTime instance
  685. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  686. * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
  687. * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
  688. * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25'
  689. * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01'
  690. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06
  691. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'utc' }),
  692. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'local' })
  693. * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }, { zone: 'America/New_York' })
  694. * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13'
  695. * @example DateTime.fromObject({ localWeekYear: 2022, localWeekNumber: 1, localWeekday: 1 }, { locale: "en-US" }).toISODate() //=> '2021-12-26'
  696. * @return {DateTime}
  697. */
  698. static fromObject(obj, opts = {}) {
  699. obj = obj || {};
  700. const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone);
  701. if (!zoneToUse.isValid) {
  702. return DateTime.invalid(unsupportedZone(zoneToUse));
  703. }
  704. const loc = Locale.fromObject(opts);
  705. const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks);
  706. const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, loc);
  707. const tsNow = Settings.now(),
  708. offsetProvis = !isUndefined(opts.specificOffset)
  709. ? opts.specificOffset
  710. : zoneToUse.offset(tsNow),
  711. containsOrdinal = !isUndefined(normalized.ordinal),
  712. containsGregorYear = !isUndefined(normalized.year),
  713. containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
  714. containsGregor = containsGregorYear || containsGregorMD,
  715. definiteWeekDef = normalized.weekYear || normalized.weekNumber;
  716. // cases:
  717. // just a weekday -> this week's instance of that weekday, no worries
  718. // (gregorian data or ordinal) + (weekYear or weekNumber) -> error
  719. // (gregorian month or day) + ordinal -> error
  720. // otherwise just use weeks or ordinals or gregorian, depending on what's specified
  721. if ((containsGregor || containsOrdinal) && definiteWeekDef) {
  722. throw new ConflictingSpecificationError(
  723. "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
  724. );
  725. }
  726. if (containsGregorMD && containsOrdinal) {
  727. throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
  728. }
  729. const useWeekData = definiteWeekDef || (normalized.weekday && !containsGregor);
  730. // configure ourselves to deal with gregorian dates or week stuff
  731. let units,
  732. defaultValues,
  733. objNow = tsToObj(tsNow, offsetProvis);
  734. if (useWeekData) {
  735. units = orderedWeekUnits;
  736. defaultValues = defaultWeekUnitValues;
  737. objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek);
  738. } else if (containsOrdinal) {
  739. units = orderedOrdinalUnits;
  740. defaultValues = defaultOrdinalUnitValues;
  741. objNow = gregorianToOrdinal(objNow);
  742. } else {
  743. units = orderedUnits;
  744. defaultValues = defaultUnitValues;
  745. }
  746. // set default values for missing stuff
  747. let foundFirst = false;
  748. for (const u of units) {
  749. const v = normalized[u];
  750. if (!isUndefined(v)) {
  751. foundFirst = true;
  752. } else if (foundFirst) {
  753. normalized[u] = defaultValues[u];
  754. } else {
  755. normalized[u] = objNow[u];
  756. }
  757. }
  758. // make sure the values we have are in range
  759. const higherOrderInvalid = useWeekData
  760. ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek)
  761. : containsOrdinal
  762. ? hasInvalidOrdinalData(normalized)
  763. : hasInvalidGregorianData(normalized),
  764. invalid = higherOrderInvalid || hasInvalidTimeData(normalized);
  765. if (invalid) {
  766. return DateTime.invalid(invalid);
  767. }
  768. // compute the actual time
  769. const gregorian = useWeekData
  770. ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek)
  771. : containsOrdinal
  772. ? ordinalToGregorian(normalized)
  773. : normalized,
  774. [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse),
  775. inst = new DateTime({
  776. ts: tsFinal,
  777. zone: zoneToUse,
  778. o: offsetFinal,
  779. loc,
  780. });
  781. // gregorian data + weekday serves only to validate
  782. if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) {
  783. return DateTime.invalid(
  784. "mismatched weekday",
  785. `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`
  786. );
  787. }
  788. if (!inst.isValid) {
  789. return DateTime.invalid(inst.invalid);
  790. }
  791. return inst;
  792. }
  793. /**
  794. * Create a DateTime from an ISO 8601 string
  795. * @param {string} text - the ISO string
  796. * @param {Object} opts - options to affect the creation
  797. * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone
  798. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
  799. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  800. * @param {string} [opts.outputCalendar] - the output calendar to set on the resulting DateTime instance
  801. * @param {string} [opts.numberingSystem] - the numbering system to set on the resulting DateTime instance
  802. * @param {string} [opts.weekSettings] - the week settings to set on the resulting DateTime instance
  803. * @example DateTime.fromISO('2016-05-25T09:08:34.123')
  804. * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00')
  805. * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true})
  806. * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'})
  807. * @example DateTime.fromISO('2016-W05-4')
  808. * @return {DateTime}
  809. */
  810. static fromISO(text, opts = {}) {
  811. const [vals, parsedZone] = parseISODate(text);
  812. return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text);
  813. }
  814. /**
  815. * Create a DateTime from an RFC 2822 string
  816. * @param {string} text - the RFC 2822 string
  817. * @param {Object} opts - options to affect the creation
  818. * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
  819. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one
  820. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  821. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  822. * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
  823. * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
  824. * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT')
  825. * @example DateTime.fromRFC2822('Fri, 25 Nov 2016 13:23:12 +0600')
  826. * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z')
  827. * @return {DateTime}
  828. */
  829. static fromRFC2822(text, opts = {}) {
  830. const [vals, parsedZone] = parseRFC2822Date(text);
  831. return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text);
  832. }
  833. /**
  834. * Create a DateTime from an HTTP header date
  835. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  836. * @param {string} text - the HTTP header date
  837. * @param {Object} opts - options to affect the creation
  838. * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in.
  839. * @param {boolean} [opts.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods.
  840. * @param {string} [opts.locale='system's locale'] - a locale to set on the resulting DateTime instance
  841. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  842. * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance
  843. * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
  844. * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT')
  845. * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT')
  846. * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994')
  847. * @return {DateTime}
  848. */
  849. static fromHTTP(text, opts = {}) {
  850. const [vals, parsedZone] = parseHTTPDate(text);
  851. return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts);
  852. }
  853. /**
  854. * Create a DateTime from an input string and format string.
  855. * Defaults to en-US if no locale has been specified, regardless of the system's locale. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/parsing?id=table-of-tokens).
  856. * @param {string} text - the string to parse
  857. * @param {string} fmt - the format the string is expected to be in (see the link below for the formats)
  858. * @param {Object} opts - options to affect the creation
  859. * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
  860. * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
  861. * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
  862. * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
  863. * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
  864. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  865. * @return {DateTime}
  866. */
  867. static fromFormat(text, fmt, opts = {}) {
  868. if (isUndefined(text) || isUndefined(fmt)) {
  869. throw new InvalidArgumentError("fromFormat requires an input string and a format");
  870. }
  871. const { locale = null, numberingSystem = null } = opts,
  872. localeToUse = Locale.fromOpts({
  873. locale,
  874. numberingSystem,
  875. defaultToEN: true,
  876. }),
  877. [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text, fmt);
  878. if (invalid) {
  879. return DateTime.invalid(invalid);
  880. } else {
  881. return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text, specificOffset);
  882. }
  883. }
  884. /**
  885. * @deprecated use fromFormat instead
  886. */
  887. static fromString(text, fmt, opts = {}) {
  888. return DateTime.fromFormat(text, fmt, opts);
  889. }
  890. /**
  891. * Create a DateTime from a SQL date, time, or datetime
  892. * Defaults to en-US if no locale has been specified, regardless of the system's locale
  893. * @param {string} text - the string to parse
  894. * @param {Object} opts - options to affect the creation
  895. * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone
  896. * @param {boolean} [opts.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one
  897. * @param {string} [opts.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale
  898. * @param {string} opts.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system
  899. * @param {string} opts.weekSettings - the week settings to set on the resulting DateTime instance
  900. * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance
  901. * @example DateTime.fromSQL('2017-05-15')
  902. * @example DateTime.fromSQL('2017-05-15 09:12:34')
  903. * @example DateTime.fromSQL('2017-05-15 09:12:34.342')
  904. * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00')
  905. * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles')
  906. * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true })
  907. * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' })
  908. * @example DateTime.fromSQL('09:12:34.342')
  909. * @return {DateTime}
  910. */
  911. static fromSQL(text, opts = {}) {
  912. const [vals, parsedZone] = parseSQL(text);
  913. return parseDataToDateTime(vals, parsedZone, opts, "SQL", text);
  914. }
  915. /**
  916. * Create an invalid DateTime.
  917. * @param {string} reason - simple string of why this DateTime is invalid. Should not contain parameters or anything else data-dependent.
  918. * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
  919. * @return {DateTime}
  920. */
  921. static invalid(reason, explanation = null) {
  922. if (!reason) {
  923. throw new InvalidArgumentError("need to specify a reason the DateTime is invalid");
  924. }
  925. const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
  926. if (Settings.throwOnInvalid) {
  927. throw new InvalidDateTimeError(invalid);
  928. } else {
  929. return new DateTime({ invalid });
  930. }
  931. }
  932. /**
  933. * Check if an object is an instance of DateTime. Works across context boundaries
  934. * @param {object} o
  935. * @return {boolean}
  936. */
  937. static isDateTime(o) {
  938. return (o && o.isLuxonDateTime) || false;
  939. }
  940. /**
  941. * Produce the format string for a set of options
  942. * @param formatOpts
  943. * @param localeOpts
  944. * @returns {string}
  945. */
  946. static parseFormatForOpts(formatOpts, localeOpts = {}) {
  947. const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts));
  948. return !tokenList ? null : tokenList.map((t) => (t ? t.val : null)).join("");
  949. }
  950. /**
  951. * Produce the the fully expanded format token for the locale
  952. * Does NOT quote characters, so quoted tokens will not round trip correctly
  953. * @param fmt
  954. * @param localeOpts
  955. * @returns {string}
  956. */
  957. static expandFormat(fmt, localeOpts = {}) {
  958. const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts));
  959. return expanded.map((t) => t.val).join("");
  960. }
  961. static resetCache() {
  962. zoneOffsetTs = undefined;
  963. zoneOffsetGuessCache = {};
  964. }
  965. // INFO
  966. /**
  967. * Get the value of unit.
  968. * @param {string} unit - a unit such as 'minute' or 'day'
  969. * @example DateTime.local(2017, 7, 4).get('month'); //=> 7
  970. * @example DateTime.local(2017, 7, 4).get('day'); //=> 4
  971. * @return {number}
  972. */
  973. get(unit) {
  974. return this[unit];
  975. }
  976. /**
  977. * Returns whether the DateTime is valid. Invalid DateTimes occur when:
  978. * * The DateTime was created from invalid calendar information, such as the 13th month or February 30
  979. * * The DateTime was created by an operation on another invalid date
  980. * @type {boolean}
  981. */
  982. get isValid() {
  983. return this.invalid === null;
  984. }
  985. /**
  986. * Returns an error code if this DateTime is invalid, or null if the DateTime is valid
  987. * @type {string}
  988. */
  989. get invalidReason() {
  990. return this.invalid ? this.invalid.reason : null;
  991. }
  992. /**
  993. * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid
  994. * @type {string}
  995. */
  996. get invalidExplanation() {
  997. return this.invalid ? this.invalid.explanation : null;
  998. }
  999. /**
  1000. * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime
  1001. *
  1002. * @type {string}
  1003. */
  1004. get locale() {
  1005. return this.isValid ? this.loc.locale : null;
  1006. }
  1007. /**
  1008. * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime
  1009. *
  1010. * @type {string}
  1011. */
  1012. get numberingSystem() {
  1013. return this.isValid ? this.loc.numberingSystem : null;
  1014. }
  1015. /**
  1016. * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime
  1017. *
  1018. * @type {string}
  1019. */
  1020. get outputCalendar() {
  1021. return this.isValid ? this.loc.outputCalendar : null;
  1022. }
  1023. /**
  1024. * Get the time zone associated with this DateTime.
  1025. * @type {Zone}
  1026. */
  1027. get zone() {
  1028. return this._zone;
  1029. }
  1030. /**
  1031. * Get the name of the time zone.
  1032. * @type {string}
  1033. */
  1034. get zoneName() {
  1035. return this.isValid ? this.zone.name : null;
  1036. }
  1037. /**
  1038. * Get the year
  1039. * @example DateTime.local(2017, 5, 25).year //=> 2017
  1040. * @type {number}
  1041. */
  1042. get year() {
  1043. return this.isValid ? this.c.year : NaN;
  1044. }
  1045. /**
  1046. * Get the quarter
  1047. * @example DateTime.local(2017, 5, 25).quarter //=> 2
  1048. * @type {number}
  1049. */
  1050. get quarter() {
  1051. return this.isValid ? Math.ceil(this.c.month / 3) : NaN;
  1052. }
  1053. /**
  1054. * Get the month (1-12).
  1055. * @example DateTime.local(2017, 5, 25).month //=> 5
  1056. * @type {number}
  1057. */
  1058. get month() {
  1059. return this.isValid ? this.c.month : NaN;
  1060. }
  1061. /**
  1062. * Get the day of the month (1-30ish).
  1063. * @example DateTime.local(2017, 5, 25).day //=> 25
  1064. * @type {number}
  1065. */
  1066. get day() {
  1067. return this.isValid ? this.c.day : NaN;
  1068. }
  1069. /**
  1070. * Get the hour of the day (0-23).
  1071. * @example DateTime.local(2017, 5, 25, 9).hour //=> 9
  1072. * @type {number}
  1073. */
  1074. get hour() {
  1075. return this.isValid ? this.c.hour : NaN;
  1076. }
  1077. /**
  1078. * Get the minute of the hour (0-59).
  1079. * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30
  1080. * @type {number}
  1081. */
  1082. get minute() {
  1083. return this.isValid ? this.c.minute : NaN;
  1084. }
  1085. /**
  1086. * Get the second of the minute (0-59).
  1087. * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52
  1088. * @type {number}
  1089. */
  1090. get second() {
  1091. return this.isValid ? this.c.second : NaN;
  1092. }
  1093. /**
  1094. * Get the millisecond of the second (0-999).
  1095. * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654
  1096. * @type {number}
  1097. */
  1098. get millisecond() {
  1099. return this.isValid ? this.c.millisecond : NaN;
  1100. }
  1101. /**
  1102. * Get the week year
  1103. * @see https://en.wikipedia.org/wiki/ISO_week_date
  1104. * @example DateTime.local(2014, 12, 31).weekYear //=> 2015
  1105. * @type {number}
  1106. */
  1107. get weekYear() {
  1108. return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN;
  1109. }
  1110. /**
  1111. * Get the week number of the week year (1-52ish).
  1112. * @see https://en.wikipedia.org/wiki/ISO_week_date
  1113. * @example DateTime.local(2017, 5, 25).weekNumber //=> 21
  1114. * @type {number}
  1115. */
  1116. get weekNumber() {
  1117. return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN;
  1118. }
  1119. /**
  1120. * Get the day of the week.
  1121. * 1 is Monday and 7 is Sunday
  1122. * @see https://en.wikipedia.org/wiki/ISO_week_date
  1123. * @example DateTime.local(2014, 11, 31).weekday //=> 4
  1124. * @type {number}
  1125. */
  1126. get weekday() {
  1127. return this.isValid ? possiblyCachedWeekData(this).weekday : NaN;
  1128. }
  1129. /**
  1130. * Returns true if this date is on a weekend according to the locale, false otherwise
  1131. * @returns {boolean}
  1132. */
  1133. get isWeekend() {
  1134. return this.isValid && this.loc.getWeekendDays().includes(this.weekday);
  1135. }
  1136. /**
  1137. * Get the day of the week according to the locale.
  1138. * 1 is the first day of the week and 7 is the last day of the week.
  1139. * If the locale assigns Sunday as the first day of the week, then a date which is a Sunday will return 1,
  1140. * @returns {number}
  1141. */
  1142. get localWeekday() {
  1143. return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN;
  1144. }
  1145. /**
  1146. * Get the week number of the week year according to the locale. Different locales assign week numbers differently,
  1147. * because the week can start on different days of the week (see localWeekday) and because a different number of days
  1148. * is required for a week to count as the first week of a year.
  1149. * @returns {number}
  1150. */
  1151. get localWeekNumber() {
  1152. return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN;
  1153. }
  1154. /**
  1155. * Get the week year according to the locale. Different locales assign week numbers (and therefor week years)
  1156. * differently, see localWeekNumber.
  1157. * @returns {number}
  1158. */
  1159. get localWeekYear() {
  1160. return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN;
  1161. }
  1162. /**
  1163. * Get the ordinal (meaning the day of the year)
  1164. * @example DateTime.local(2017, 5, 25).ordinal //=> 145
  1165. * @type {number|DateTime}
  1166. */
  1167. get ordinal() {
  1168. return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN;
  1169. }
  1170. /**
  1171. * Get the human readable short month name, such as 'Oct'.
  1172. * Defaults to the system's locale if no locale has been specified
  1173. * @example DateTime.local(2017, 10, 30).monthShort //=> Oct
  1174. * @type {string}
  1175. */
  1176. get monthShort() {
  1177. return this.isValid ? Info.months("short", { locObj: this.loc })[this.month - 1] : null;
  1178. }
  1179. /**
  1180. * Get the human readable long month name, such as 'October'.
  1181. * Defaults to the system's locale if no locale has been specified
  1182. * @example DateTime.local(2017, 10, 30).monthLong //=> October
  1183. * @type {string}
  1184. */
  1185. get monthLong() {
  1186. return this.isValid ? Info.months("long", { locObj: this.loc })[this.month - 1] : null;
  1187. }
  1188. /**
  1189. * Get the human readable short weekday, such as 'Mon'.
  1190. * Defaults to the system's locale if no locale has been specified
  1191. * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon
  1192. * @type {string}
  1193. */
  1194. get weekdayShort() {
  1195. return this.isValid ? Info.weekdays("short", { locObj: this.loc })[this.weekday - 1] : null;
  1196. }
  1197. /**
  1198. * Get the human readable long weekday, such as 'Monday'.
  1199. * Defaults to the system's locale if no locale has been specified
  1200. * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday
  1201. * @type {string}
  1202. */
  1203. get weekdayLong() {
  1204. return this.isValid ? Info.weekdays("long", { locObj: this.loc })[this.weekday - 1] : null;
  1205. }
  1206. /**
  1207. * Get the UTC offset of this DateTime in minutes
  1208. * @example DateTime.now().offset //=> -240
  1209. * @example DateTime.utc().offset //=> 0
  1210. * @type {number}
  1211. */
  1212. get offset() {
  1213. return this.isValid ? +this.o : NaN;
  1214. }
  1215. /**
  1216. * Get the short human name for the zone's current offset, for example "EST" or "EDT".
  1217. * Defaults to the system's locale if no locale has been specified
  1218. * @type {string}
  1219. */
  1220. get offsetNameShort() {
  1221. if (this.isValid) {
  1222. return this.zone.offsetName(this.ts, {
  1223. format: "short",
  1224. locale: this.locale,
  1225. });
  1226. } else {
  1227. return null;
  1228. }
  1229. }
  1230. /**
  1231. * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time".
  1232. * Defaults to the system's locale if no locale has been specified
  1233. * @type {string}
  1234. */
  1235. get offsetNameLong() {
  1236. if (this.isValid) {
  1237. return this.zone.offsetName(this.ts, {
  1238. format: "long",
  1239. locale: this.locale,
  1240. });
  1241. } else {
  1242. return null;
  1243. }
  1244. }
  1245. /**
  1246. * Get whether this zone's offset ever changes, as in a DST.
  1247. * @type {boolean}
  1248. */
  1249. get isOffsetFixed() {
  1250. return this.isValid ? this.zone.isUniversal : null;
  1251. }
  1252. /**
  1253. * Get whether the DateTime is in a DST.
  1254. * @type {boolean}
  1255. */
  1256. get isInDST() {
  1257. if (this.isOffsetFixed) {
  1258. return false;
  1259. } else {
  1260. return (
  1261. this.offset > this.set({ month: 1, day: 1 }).offset ||
  1262. this.offset > this.set({ month: 5 }).offset
  1263. );
  1264. }
  1265. }
  1266. /**
  1267. * Get those DateTimes which have the same local time as this DateTime, but a different offset from UTC
  1268. * in this DateTime's zone. During DST changes local time can be ambiguous, for example
  1269. * `2023-10-29T02:30:00` in `Europe/Berlin` can have offset `+01:00` or `+02:00`.
  1270. * This method will return both possible DateTimes if this DateTime's local time is ambiguous.
  1271. * @returns {DateTime[]}
  1272. */
  1273. getPossibleOffsets() {
  1274. if (!this.isValid || this.isOffsetFixed) {
  1275. return [this];
  1276. }
  1277. const dayMs = 86400000;
  1278. const minuteMs = 60000;
  1279. const localTS = objToLocalTS(this.c);
  1280. const oEarlier = this.zone.offset(localTS - dayMs);
  1281. const oLater = this.zone.offset(localTS + dayMs);
  1282. const o1 = this.zone.offset(localTS - oEarlier * minuteMs);
  1283. const o2 = this.zone.offset(localTS - oLater * minuteMs);
  1284. if (o1 === o2) {
  1285. return [this];
  1286. }
  1287. const ts1 = localTS - o1 * minuteMs;
  1288. const ts2 = localTS - o2 * minuteMs;
  1289. const c1 = tsToObj(ts1, o1);
  1290. const c2 = tsToObj(ts2, o2);
  1291. if (
  1292. c1.hour === c2.hour &&
  1293. c1.minute === c2.minute &&
  1294. c1.second === c2.second &&
  1295. c1.millisecond === c2.millisecond
  1296. ) {
  1297. return [clone(this, { ts: ts1 }), clone(this, { ts: ts2 })];
  1298. }
  1299. return [this];
  1300. }
  1301. /**
  1302. * Returns true if this DateTime is in a leap year, false otherwise
  1303. * @example DateTime.local(2016).isInLeapYear //=> true
  1304. * @example DateTime.local(2013).isInLeapYear //=> false
  1305. * @type {boolean}
  1306. */
  1307. get isInLeapYear() {
  1308. return isLeapYear(this.year);
  1309. }
  1310. /**
  1311. * Returns the number of days in this DateTime's month
  1312. * @example DateTime.local(2016, 2).daysInMonth //=> 29
  1313. * @example DateTime.local(2016, 3).daysInMonth //=> 31
  1314. * @type {number}
  1315. */
  1316. get daysInMonth() {
  1317. return daysInMonth(this.year, this.month);
  1318. }
  1319. /**
  1320. * Returns the number of days in this DateTime's year
  1321. * @example DateTime.local(2016).daysInYear //=> 366
  1322. * @example DateTime.local(2013).daysInYear //=> 365
  1323. * @type {number}
  1324. */
  1325. get daysInYear() {
  1326. return this.isValid ? daysInYear(this.year) : NaN;
  1327. }
  1328. /**
  1329. * Returns the number of weeks in this DateTime's year
  1330. * @see https://en.wikipedia.org/wiki/ISO_week_date
  1331. * @example DateTime.local(2004).weeksInWeekYear //=> 53
  1332. * @example DateTime.local(2013).weeksInWeekYear //=> 52
  1333. * @type {number}
  1334. */
  1335. get weeksInWeekYear() {
  1336. return this.isValid ? weeksInWeekYear(this.weekYear) : NaN;
  1337. }
  1338. /**
  1339. * Returns the number of weeks in this DateTime's local week year
  1340. * @example DateTime.local(2020, 6, {locale: 'en-US'}).weeksInLocalWeekYear //=> 52
  1341. * @example DateTime.local(2020, 6, {locale: 'de-DE'}).weeksInLocalWeekYear //=> 53
  1342. * @type {number}
  1343. */
  1344. get weeksInLocalWeekYear() {
  1345. return this.isValid
  1346. ? weeksInWeekYear(
  1347. this.localWeekYear,
  1348. this.loc.getMinDaysInFirstWeek(),
  1349. this.loc.getStartOfWeek()
  1350. )
  1351. : NaN;
  1352. }
  1353. /**
  1354. * Returns the resolved Intl options for this DateTime.
  1355. * This is useful in understanding the behavior of formatting methods
  1356. * @param {Object} opts - the same options as toLocaleString
  1357. * @return {Object}
  1358. */
  1359. resolvedLocaleOptions(opts = {}) {
  1360. const { locale, numberingSystem, calendar } = Formatter.create(
  1361. this.loc.clone(opts),
  1362. opts
  1363. ).resolvedOptions(this);
  1364. return { locale, numberingSystem, outputCalendar: calendar };
  1365. }
  1366. // TRANSFORM
  1367. /**
  1368. * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime.
  1369. *
  1370. * Equivalent to {@link DateTime#setZone}('utc')
  1371. * @param {number} [offset=0] - optionally, an offset from UTC in minutes
  1372. * @param {Object} [opts={}] - options to pass to `setZone()`
  1373. * @return {DateTime}
  1374. */
  1375. toUTC(offset = 0, opts = {}) {
  1376. return this.setZone(FixedOffsetZone.instance(offset), opts);
  1377. }
  1378. /**
  1379. * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime.
  1380. *
  1381. * Equivalent to `setZone('local')`
  1382. * @return {DateTime}
  1383. */
  1384. toLocal() {
  1385. return this.setZone(Settings.defaultZone);
  1386. }
  1387. /**
  1388. * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime.
  1389. *
  1390. * By default, the setter keeps the underlying time the same (as in, the same timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link DateTime#plus}. You may wish to use {@link DateTime#toLocal} and {@link DateTime#toUTC} which provide simple convenience wrappers for commonly used zones.
  1391. * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'UTC+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link DateTime#Zone} class.
  1392. * @param {Object} opts - options
  1393. * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this.
  1394. * @return {DateTime}
  1395. */
  1396. setZone(zone, { keepLocalTime = false, keepCalendarTime = false } = {}) {
  1397. zone = normalizeZone(zone, Settings.defaultZone);
  1398. if (zone.equals(this.zone)) {
  1399. return this;
  1400. } else if (!zone.isValid) {
  1401. return DateTime.invalid(unsupportedZone(zone));
  1402. } else {
  1403. let newTS = this.ts;
  1404. if (keepLocalTime || keepCalendarTime) {
  1405. const offsetGuess = zone.offset(this.ts);
  1406. const asObj = this.toObject();
  1407. [newTS] = objToTS(asObj, offsetGuess, zone);
  1408. }
  1409. return clone(this, { ts: newTS, zone });
  1410. }
  1411. }
  1412. /**
  1413. * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime.
  1414. * @param {Object} properties - the properties to set
  1415. * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' })
  1416. * @return {DateTime}
  1417. */
  1418. reconfigure({ locale, numberingSystem, outputCalendar } = {}) {
  1419. const loc = this.loc.clone({ locale, numberingSystem, outputCalendar });
  1420. return clone(this, { loc });
  1421. }
  1422. /**
  1423. * "Set" the locale. Returns a newly-constructed DateTime.
  1424. * Just a convenient alias for reconfigure({ locale })
  1425. * @example DateTime.local(2017, 5, 25).setLocale('en-GB')
  1426. * @return {DateTime}
  1427. */
  1428. setLocale(locale) {
  1429. return this.reconfigure({ locale });
  1430. }
  1431. /**
  1432. * "Set" the values of specified units. Returns a newly-constructed DateTime.
  1433. * You can only set units with this method; for "setting" metadata, see {@link DateTime#reconfigure} and {@link DateTime#setZone}.
  1434. *
  1435. * This method also supports setting locale-based week units, i.e. `localWeekday`, `localWeekNumber` and `localWeekYear`.
  1436. * They cannot be mixed with ISO-week units like `weekday`.
  1437. * @param {Object} values - a mapping of units to numbers
  1438. * @example dt.set({ year: 2017 })
  1439. * @example dt.set({ hour: 8, minute: 30 })
  1440. * @example dt.set({ weekday: 5 })
  1441. * @example dt.set({ year: 2005, ordinal: 234 })
  1442. * @return {DateTime}
  1443. */
  1444. set(values) {
  1445. if (!this.isValid) return this;
  1446. const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks);
  1447. const { minDaysInFirstWeek, startOfWeek } = usesLocalWeekValues(normalized, this.loc);
  1448. const settingWeekStuff =
  1449. !isUndefined(normalized.weekYear) ||
  1450. !isUndefined(normalized.weekNumber) ||
  1451. !isUndefined(normalized.weekday),
  1452. containsOrdinal = !isUndefined(normalized.ordinal),
  1453. containsGregorYear = !isUndefined(normalized.year),
  1454. containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day),
  1455. containsGregor = containsGregorYear || containsGregorMD,
  1456. definiteWeekDef = normalized.weekYear || normalized.weekNumber;
  1457. if ((containsGregor || containsOrdinal) && definiteWeekDef) {
  1458. throw new ConflictingSpecificationError(
  1459. "Can't mix weekYear/weekNumber units with year/month/day or ordinals"
  1460. );
  1461. }
  1462. if (containsGregorMD && containsOrdinal) {
  1463. throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day");
  1464. }
  1465. let mixed;
  1466. if (settingWeekStuff) {
  1467. mixed = weekToGregorian(
  1468. { ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), ...normalized },
  1469. minDaysInFirstWeek,
  1470. startOfWeek
  1471. );
  1472. } else if (!isUndefined(normalized.ordinal)) {
  1473. mixed = ordinalToGregorian({ ...gregorianToOrdinal(this.c), ...normalized });
  1474. } else {
  1475. mixed = { ...this.toObject(), ...normalized };
  1476. // if we didn't set the day but we ended up on an overflow date,
  1477. // use the last day of the right month
  1478. if (isUndefined(normalized.day)) {
  1479. mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day);
  1480. }
  1481. }
  1482. const [ts, o] = objToTS(mixed, this.o, this.zone);
  1483. return clone(this, { ts, o });
  1484. }
  1485. /**
  1486. * Add a period of time to this DateTime and return the resulting DateTime
  1487. *
  1488. * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between.
  1489. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  1490. * @example DateTime.now().plus(123) //~> in 123 milliseconds
  1491. * @example DateTime.now().plus({ minutes: 15 }) //~> in 15 minutes
  1492. * @example DateTime.now().plus({ days: 1 }) //~> this time tomorrow
  1493. * @example DateTime.now().plus({ days: -1 }) //~> this time yesterday
  1494. * @example DateTime.now().plus({ hours: 3, minutes: 13 }) //~> in 3 hr, 13 min
  1495. * @example DateTime.now().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 3 hr, 13 min
  1496. * @return {DateTime}
  1497. */
  1498. plus(duration) {
  1499. if (!this.isValid) return this;
  1500. const dur = Duration.fromDurationLike(duration);
  1501. return clone(this, adjustTime(this, dur));
  1502. }
  1503. /**
  1504. * Subtract a period of time to this DateTime and return the resulting DateTime
  1505. * See {@link DateTime#plus}
  1506. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
  1507. @return {DateTime}
  1508. */
  1509. minus(duration) {
  1510. if (!this.isValid) return this;
  1511. const dur = Duration.fromDurationLike(duration).negate();
  1512. return clone(this, adjustTime(this, dur));
  1513. }
  1514. /**
  1515. * "Set" this DateTime to the beginning of a unit of time.
  1516. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
  1517. * @param {Object} opts - options
  1518. * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
  1519. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01'
  1520. * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01'
  1521. * @example DateTime.local(2014, 3, 3).startOf('week').toISODate(); //=> '2014-03-03', weeks always start on Mondays
  1522. * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00'
  1523. * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00'
  1524. * @return {DateTime}
  1525. */
  1526. startOf(unit, { useLocaleWeeks = false } = {}) {
  1527. if (!this.isValid) return this;
  1528. const o = {},
  1529. normalizedUnit = Duration.normalizeUnit(unit);
  1530. switch (normalizedUnit) {
  1531. case "years":
  1532. o.month = 1;
  1533. // falls through
  1534. case "quarters":
  1535. case "months":
  1536. o.day = 1;
  1537. // falls through
  1538. case "weeks":
  1539. case "days":
  1540. o.hour = 0;
  1541. // falls through
  1542. case "hours":
  1543. o.minute = 0;
  1544. // falls through
  1545. case "minutes":
  1546. o.second = 0;
  1547. // falls through
  1548. case "seconds":
  1549. o.millisecond = 0;
  1550. break;
  1551. case "milliseconds":
  1552. break;
  1553. // no default, invalid units throw in normalizeUnit()
  1554. }
  1555. if (normalizedUnit === "weeks") {
  1556. if (useLocaleWeeks) {
  1557. const startOfWeek = this.loc.getStartOfWeek();
  1558. const { weekday } = this;
  1559. if (weekday < startOfWeek) {
  1560. o.weekNumber = this.weekNumber - 1;
  1561. }
  1562. o.weekday = startOfWeek;
  1563. } else {
  1564. o.weekday = 1;
  1565. }
  1566. }
  1567. if (normalizedUnit === "quarters") {
  1568. const q = Math.ceil(this.month / 3);
  1569. o.month = (q - 1) * 3 + 1;
  1570. }
  1571. return this.set(o);
  1572. }
  1573. /**
  1574. * "Set" this DateTime to the end (meaning the last millisecond) of a unit of time
  1575. * @param {string} unit - The unit to go to the end of. Can be 'year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second', or 'millisecond'.
  1576. * @param {Object} opts - options
  1577. * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week
  1578. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00'
  1579. * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00'
  1580. * @example DateTime.local(2014, 3, 3).endOf('week').toISO(); // => '2014-03-09T23:59:59.999-05:00', weeks start on Mondays
  1581. * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00'
  1582. * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00'
  1583. * @return {DateTime}
  1584. */
  1585. endOf(unit, opts) {
  1586. return this.isValid
  1587. ? this.plus({ [unit]: 1 })
  1588. .startOf(unit, opts)
  1589. .minus(1)
  1590. : this;
  1591. }
  1592. // OUTPUT
  1593. /**
  1594. * Returns a string representation of this DateTime formatted according to the specified format string.
  1595. * **You may not want this.** See {@link DateTime#toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/#/formatting?id=table-of-tokens).
  1596. * Defaults to en-US if no locale has been specified, regardless of the system's locale.
  1597. * @param {string} fmt - the format string
  1598. * @param {Object} opts - opts to override the configuration options on this DateTime
  1599. * @example DateTime.now().toFormat('yyyy LLL dd') //=> '2017 Apr 22'
  1600. * @example DateTime.now().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22'
  1601. * @example DateTime.now().toFormat('yyyy LLL dd', { locale: "fr" }) //=> '2017 avr. 22'
  1602. * @example DateTime.now().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes'
  1603. * @return {string}
  1604. */
  1605. toFormat(fmt, opts = {}) {
  1606. return this.isValid
  1607. ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt)
  1608. : INVALID;
  1609. }
  1610. /**
  1611. * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`.
  1612. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation
  1613. * of the DateTime in the assigned locale.
  1614. * Defaults to the system's locale if no locale has been specified
  1615. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat
  1616. * @param formatOpts {Object} - Intl.DateTimeFormat constructor options and configuration options
  1617. * @param {Object} opts - opts to override the configuration options on this DateTime
  1618. * @example DateTime.now().toLocaleString(); //=> 4/20/2017
  1619. * @example DateTime.now().setLocale('en-gb').toLocaleString(); //=> '20/04/2017'
  1620. * @example DateTime.now().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017'
  1621. * @example DateTime.now().toLocaleString(DateTime.DATE_FULL, { locale: 'fr' }); //=> '28 août 2022'
  1622. * @example DateTime.now().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM'
  1623. * @example DateTime.now().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM'
  1624. * @example DateTime.now().toLocaleString({ weekday: 'long', month: 'long', day: '2-digit' }); //=> 'Thursday, April 20'
  1625. * @example DateTime.now().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }); //=> 'Thu, Apr 20, 11:27 AM'
  1626. * @example DateTime.now().toLocaleString({ hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }); //=> '11:32'
  1627. * @return {string}
  1628. */
  1629. toLocaleString(formatOpts = Formats.DATE_SHORT, opts = {}) {
  1630. return this.isValid
  1631. ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this)
  1632. : INVALID;
  1633. }
  1634. /**
  1635. * Returns an array of format "parts", meaning individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output.
  1636. * Defaults to the system's locale if no locale has been specified
  1637. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts
  1638. * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`.
  1639. * @example DateTime.now().toLocaleParts(); //=> [
  1640. * //=> { type: 'day', value: '25' },
  1641. * //=> { type: 'literal', value: '/' },
  1642. * //=> { type: 'month', value: '05' },
  1643. * //=> { type: 'literal', value: '/' },
  1644. * //=> { type: 'year', value: '1982' }
  1645. * //=> ]
  1646. */
  1647. toLocaleParts(opts = {}) {
  1648. return this.isValid
  1649. ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this)
  1650. : [];
  1651. }
  1652. /**
  1653. * Returns an ISO 8601-compliant string representation of this DateTime
  1654. * @param {Object} opts - options
  1655. * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
  1656. * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
  1657. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  1658. * @param {boolean} [opts.extendedZone=false] - add the time zone format extension
  1659. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  1660. * @example DateTime.utc(1983, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z'
  1661. * @example DateTime.now().toISO() //=> '2017-04-22T20:47:05.335-04:00'
  1662. * @example DateTime.now().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335'
  1663. * @example DateTime.now().toISO({ format: 'basic' }) //=> '20170422T204705.335-0400'
  1664. * @return {string}
  1665. */
  1666. toISO({
  1667. format = "extended",
  1668. suppressSeconds = false,
  1669. suppressMilliseconds = false,
  1670. includeOffset = true,
  1671. extendedZone = false,
  1672. } = {}) {
  1673. if (!this.isValid) {
  1674. return null;
  1675. }
  1676. const ext = format === "extended";
  1677. let c = toISODate(this, ext);
  1678. c += "T";
  1679. c += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone);
  1680. return c;
  1681. }
  1682. /**
  1683. * Returns an ISO 8601-compliant string representation of this DateTime's date component
  1684. * @param {Object} opts - options
  1685. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  1686. * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25'
  1687. * @example DateTime.utc(1982, 5, 25).toISODate({ format: 'basic' }) //=> '19820525'
  1688. * @return {string}
  1689. */
  1690. toISODate({ format = "extended" } = {}) {
  1691. if (!this.isValid) {
  1692. return null;
  1693. }
  1694. return toISODate(this, format === "extended");
  1695. }
  1696. /**
  1697. * Returns an ISO 8601-compliant string representation of this DateTime's week date
  1698. * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2'
  1699. * @return {string}
  1700. */
  1701. toISOWeekDate() {
  1702. return toTechFormat(this, "kkkk-'W'WW-c");
  1703. }
  1704. /**
  1705. * Returns an ISO 8601-compliant string representation of this DateTime's time component
  1706. * @param {Object} opts - options
  1707. * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
  1708. * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
  1709. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  1710. * @param {boolean} [opts.extendedZone=true] - add the time zone format extension
  1711. * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
  1712. * @param {string} [opts.format='extended'] - choose between the basic and extended format
  1713. * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime() //=> '07:34:19.361Z'
  1714. * @example DateTime.utc().set({ hour: 7, minute: 34, seconds: 0, milliseconds: 0 }).toISOTime({ suppressSeconds: true }) //=> '07:34Z'
  1715. * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ format: 'basic' }) //=> '073419.361Z'
  1716. * @example DateTime.utc().set({ hour: 7, minute: 34 }).toISOTime({ includePrefix: true }) //=> 'T07:34:19.361Z'
  1717. * @return {string}
  1718. */
  1719. toISOTime({
  1720. suppressMilliseconds = false,
  1721. suppressSeconds = false,
  1722. includeOffset = true,
  1723. includePrefix = false,
  1724. extendedZone = false,
  1725. format = "extended",
  1726. } = {}) {
  1727. if (!this.isValid) {
  1728. return null;
  1729. }
  1730. let c = includePrefix ? "T" : "";
  1731. return (
  1732. c +
  1733. toISOTime(
  1734. this,
  1735. format === "extended",
  1736. suppressSeconds,
  1737. suppressMilliseconds,
  1738. includeOffset,
  1739. extendedZone
  1740. )
  1741. );
  1742. }
  1743. /**
  1744. * Returns an RFC 2822-compatible string representation of this DateTime
  1745. * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000'
  1746. * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400'
  1747. * @return {string}
  1748. */
  1749. toRFC2822() {
  1750. return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false);
  1751. }
  1752. /**
  1753. * Returns a string representation of this DateTime appropriate for use in HTTP headers. The output is always expressed in GMT.
  1754. * Specifically, the string conforms to RFC 1123.
  1755. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  1756. * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT'
  1757. * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT'
  1758. * @return {string}
  1759. */
  1760. toHTTP() {
  1761. return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'");
  1762. }
  1763. /**
  1764. * Returns a string representation of this DateTime appropriate for use in SQL Date
  1765. * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13'
  1766. * @return {string}
  1767. */
  1768. toSQLDate() {
  1769. if (!this.isValid) {
  1770. return null;
  1771. }
  1772. return toISODate(this, true);
  1773. }
  1774. /**
  1775. * Returns a string representation of this DateTime appropriate for use in SQL Time
  1776. * @param {Object} opts - options
  1777. * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
  1778. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  1779. * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
  1780. * @example DateTime.utc().toSQL() //=> '05:15:16.345'
  1781. * @example DateTime.now().toSQL() //=> '05:15:16.345 -04:00'
  1782. * @example DateTime.now().toSQL({ includeOffset: false }) //=> '05:15:16.345'
  1783. * @example DateTime.now().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York'
  1784. * @return {string}
  1785. */
  1786. toSQLTime({ includeOffset = true, includeZone = false, includeOffsetSpace = true } = {}) {
  1787. let fmt = "HH:mm:ss.SSS";
  1788. if (includeZone || includeOffset) {
  1789. if (includeOffsetSpace) {
  1790. fmt += " ";
  1791. }
  1792. if (includeZone) {
  1793. fmt += "z";
  1794. } else if (includeOffset) {
  1795. fmt += "ZZ";
  1796. }
  1797. }
  1798. return toTechFormat(this, fmt, true);
  1799. }
  1800. /**
  1801. * Returns a string representation of this DateTime appropriate for use in SQL DateTime
  1802. * @param {Object} opts - options
  1803. * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset.
  1804. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00'
  1805. * @param {boolean} [opts.includeOffsetSpace=true] - include the space between the time and the offset, such as '05:15:16.345 -04:00'
  1806. * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z'
  1807. * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00'
  1808. * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000'
  1809. * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: true }) //=> '2014-07-13 00:00:00.000 America/New_York'
  1810. * @return {string}
  1811. */
  1812. toSQL(opts = {}) {
  1813. if (!this.isValid) {
  1814. return null;
  1815. }
  1816. return `${this.toSQLDate()} ${this.toSQLTime(opts)}`;
  1817. }
  1818. /**
  1819. * Returns a string representation of this DateTime appropriate for debugging
  1820. * @return {string}
  1821. */
  1822. toString() {
  1823. return this.isValid ? this.toISO() : INVALID;
  1824. }
  1825. /**
  1826. * Returns a string representation of this DateTime appropriate for the REPL.
  1827. * @return {string}
  1828. */
  1829. [Symbol.for("nodejs.util.inspect.custom")]() {
  1830. if (this.isValid) {
  1831. return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;
  1832. } else {
  1833. return `DateTime { Invalid, reason: ${this.invalidReason} }`;
  1834. }
  1835. }
  1836. /**
  1837. * Returns the epoch milliseconds of this DateTime. Alias of {@link DateTime#toMillis}
  1838. * @return {number}
  1839. */
  1840. valueOf() {
  1841. return this.toMillis();
  1842. }
  1843. /**
  1844. * Returns the epoch milliseconds of this DateTime.
  1845. * @return {number}
  1846. */
  1847. toMillis() {
  1848. return this.isValid ? this.ts : NaN;
  1849. }
  1850. /**
  1851. * Returns the epoch seconds of this DateTime.
  1852. * @return {number}
  1853. */
  1854. toSeconds() {
  1855. return this.isValid ? this.ts / 1000 : NaN;
  1856. }
  1857. /**
  1858. * Returns the epoch seconds (as a whole number) of this DateTime.
  1859. * @return {number}
  1860. */
  1861. toUnixInteger() {
  1862. return this.isValid ? Math.floor(this.ts / 1000) : NaN;
  1863. }
  1864. /**
  1865. * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON.
  1866. * @return {string}
  1867. */
  1868. toJSON() {
  1869. return this.toISO();
  1870. }
  1871. /**
  1872. * Returns a BSON serializable equivalent to this DateTime.
  1873. * @return {Date}
  1874. */
  1875. toBSON() {
  1876. return this.toJSDate();
  1877. }
  1878. /**
  1879. * Returns a JavaScript object with this DateTime's year, month, day, and so on.
  1880. * @param opts - options for generating the object
  1881. * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output
  1882. * @example DateTime.now().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 }
  1883. * @return {Object}
  1884. */
  1885. toObject(opts = {}) {
  1886. if (!this.isValid) return {};
  1887. const base = { ...this.c };
  1888. if (opts.includeConfig) {
  1889. base.outputCalendar = this.outputCalendar;
  1890. base.numberingSystem = this.loc.numberingSystem;
  1891. base.locale = this.loc.locale;
  1892. }
  1893. return base;
  1894. }
  1895. /**
  1896. * Returns a JavaScript Date equivalent to this DateTime.
  1897. * @return {Date}
  1898. */
  1899. toJSDate() {
  1900. return new Date(this.isValid ? this.ts : NaN);
  1901. }
  1902. // COMPARE
  1903. /**
  1904. * Return the difference between two DateTimes as a Duration.
  1905. * @param {DateTime} otherDateTime - the DateTime to compare this one to
  1906. * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration.
  1907. * @param {Object} opts - options that affect the creation of the Duration
  1908. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  1909. * @example
  1910. * var i1 = DateTime.fromISO('1982-05-25T09:45'),
  1911. * i2 = DateTime.fromISO('1983-10-14T10:30');
  1912. * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 }
  1913. * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 }
  1914. * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 }
  1915. * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 }
  1916. * @return {Duration}
  1917. */
  1918. diff(otherDateTime, unit = "milliseconds", opts = {}) {
  1919. if (!this.isValid || !otherDateTime.isValid) {
  1920. return Duration.invalid("created by diffing an invalid DateTime");
  1921. }
  1922. const durOpts = { locale: this.locale, numberingSystem: this.numberingSystem, ...opts };
  1923. const units = maybeArray(unit).map(Duration.normalizeUnit),
  1924. otherIsLater = otherDateTime.valueOf() > this.valueOf(),
  1925. earlier = otherIsLater ? this : otherDateTime,
  1926. later = otherIsLater ? otherDateTime : this,
  1927. diffed = diff(earlier, later, units, durOpts);
  1928. return otherIsLater ? diffed.negate() : diffed;
  1929. }
  1930. /**
  1931. * Return the difference between this DateTime and right now.
  1932. * See {@link DateTime#diff}
  1933. * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration
  1934. * @param {Object} opts - options that affect the creation of the Duration
  1935. * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
  1936. * @return {Duration}
  1937. */
  1938. diffNow(unit = "milliseconds", opts = {}) {
  1939. return this.diff(DateTime.now(), unit, opts);
  1940. }
  1941. /**
  1942. * Return an Interval spanning between this DateTime and another DateTime
  1943. * @param {DateTime} otherDateTime - the other end point of the Interval
  1944. * @return {Interval}
  1945. */
  1946. until(otherDateTime) {
  1947. return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this;
  1948. }
  1949. /**
  1950. * Return whether this DateTime is in the same unit of time as another DateTime.
  1951. * Higher-order units must also be identical for this function to return `true`.
  1952. * Note that time zones are **ignored** in this comparison, which compares the **local** calendar time. Use {@link DateTime#setZone} to convert one of the dates if needed.
  1953. * @param {DateTime} otherDateTime - the other DateTime
  1954. * @param {string} unit - the unit of time to check sameness on
  1955. * @param {Object} opts - options
  1956. * @param {boolean} [opts.useLocaleWeeks=false] - If true, use weeks based on the locale, i.e. use the locale-dependent start of the week; only the locale of this DateTime is used
  1957. * @example DateTime.now().hasSame(otherDT, 'day'); //~> true if otherDT is in the same current calendar day
  1958. * @return {boolean}
  1959. */
  1960. hasSame(otherDateTime, unit, opts) {
  1961. if (!this.isValid) return false;
  1962. const inputMs = otherDateTime.valueOf();
  1963. const adjustedToZone = this.setZone(otherDateTime.zone, { keepLocalTime: true });
  1964. return (
  1965. adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts)
  1966. );
  1967. }
  1968. /**
  1969. * Equality check
  1970. * Two DateTimes are equal if and only if they represent the same millisecond, have the same zone and location, and are both valid.
  1971. * To compare just the millisecond values, use `+dt1 === +dt2`.
  1972. * @param {DateTime} other - the other DateTime
  1973. * @return {boolean}
  1974. */
  1975. equals(other) {
  1976. return (
  1977. this.isValid &&
  1978. other.isValid &&
  1979. this.valueOf() === other.valueOf() &&
  1980. this.zone.equals(other.zone) &&
  1981. this.loc.equals(other.loc)
  1982. );
  1983. }
  1984. /**
  1985. * Returns a string representation of a this time relative to now, such as "in two days". Can only internationalize if your
  1986. * platform supports Intl.RelativeTimeFormat. Rounds down by default.
  1987. * @param {Object} options - options that affect the output
  1988. * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
  1989. * @param {string} [options.style="long"] - the style of units, must be "long", "short", or "narrow"
  1990. * @param {string|string[]} options.unit - use a specific unit or array of units; if omitted, or an array, the method will pick the best unit. Use an array or one of "years", "quarters", "months", "weeks", "days", "hours", "minutes", or "seconds"
  1991. * @param {boolean} [options.round=true] - whether to round the numbers in the output.
  1992. * @param {number} [options.padding=0] - padding in milliseconds. This allows you to round up the result if it fits inside the threshold. Don't use in combination with {round: false} because the decimal output will include the padding.
  1993. * @param {string} options.locale - override the locale of this DateTime
  1994. * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
  1995. * @example DateTime.now().plus({ days: 1 }).toRelative() //=> "in 1 day"
  1996. * @example DateTime.now().setLocale("es").toRelative({ days: 1 }) //=> "dentro de 1 día"
  1997. * @example DateTime.now().plus({ days: 1 }).toRelative({ locale: "fr" }) //=> "dans 23 heures"
  1998. * @example DateTime.now().minus({ days: 2 }).toRelative() //=> "2 days ago"
  1999. * @example DateTime.now().minus({ days: 2 }).toRelative({ unit: "hours" }) //=> "48 hours ago"
  2000. * @example DateTime.now().minus({ hours: 36 }).toRelative({ round: false }) //=> "1.5 days ago"
  2001. */
  2002. toRelative(options = {}) {
  2003. if (!this.isValid) return null;
  2004. const base = options.base || DateTime.fromObject({}, { zone: this.zone }),
  2005. padding = options.padding ? (this < base ? -options.padding : options.padding) : 0;
  2006. let units = ["years", "months", "days", "hours", "minutes", "seconds"];
  2007. let unit = options.unit;
  2008. if (Array.isArray(options.unit)) {
  2009. units = options.unit;
  2010. unit = undefined;
  2011. }
  2012. return diffRelative(base, this.plus(padding), {
  2013. ...options,
  2014. numeric: "always",
  2015. units,
  2016. unit,
  2017. });
  2018. }
  2019. /**
  2020. * Returns a string representation of this date relative to today, such as "yesterday" or "next month".
  2021. * Only internationalizes on platforms that supports Intl.RelativeTimeFormat.
  2022. * @param {Object} options - options that affect the output
  2023. * @param {DateTime} [options.base=DateTime.now()] - the DateTime to use as the basis to which this time is compared. Defaults to now.
  2024. * @param {string} options.locale - override the locale of this DateTime
  2025. * @param {string} options.unit - use a specific unit; if omitted, the method will pick the unit. Use one of "years", "quarters", "months", "weeks", or "days"
  2026. * @param {string} options.numberingSystem - override the numberingSystem of this DateTime. The Intl system may choose not to honor this
  2027. * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar() //=> "tomorrow"
  2028. * @example DateTime.now().setLocale("es").plus({ days: 1 }).toRelative() //=> ""mañana"
  2029. * @example DateTime.now().plus({ days: 1 }).toRelativeCalendar({ locale: "fr" }) //=> "demain"
  2030. * @example DateTime.now().minus({ days: 2 }).toRelativeCalendar() //=> "2 days ago"
  2031. */
  2032. toRelativeCalendar(options = {}) {
  2033. if (!this.isValid) return null;
  2034. return diffRelative(options.base || DateTime.fromObject({}, { zone: this.zone }), this, {
  2035. ...options,
  2036. numeric: "auto",
  2037. units: ["years", "months", "days"],
  2038. calendary: true,
  2039. });
  2040. }
  2041. /**
  2042. * Return the min of several date times
  2043. * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum
  2044. * @return {DateTime} the min DateTime, or undefined if called with no argument
  2045. */
  2046. static min(...dateTimes) {
  2047. if (!dateTimes.every(DateTime.isDateTime)) {
  2048. throw new InvalidArgumentError("min requires all arguments be DateTimes");
  2049. }
  2050. return bestBy(dateTimes, (i) => i.valueOf(), Math.min);
  2051. }
  2052. /**
  2053. * Return the max of several date times
  2054. * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum
  2055. * @return {DateTime} the max DateTime, or undefined if called with no argument
  2056. */
  2057. static max(...dateTimes) {
  2058. if (!dateTimes.every(DateTime.isDateTime)) {
  2059. throw new InvalidArgumentError("max requires all arguments be DateTimes");
  2060. }
  2061. return bestBy(dateTimes, (i) => i.valueOf(), Math.max);
  2062. }
  2063. // MISC
  2064. /**
  2065. * Explain how a string would be parsed by fromFormat()
  2066. * @param {string} text - the string to parse
  2067. * @param {string} fmt - the format the string is expected to be in (see description)
  2068. * @param {Object} options - options taken by fromFormat()
  2069. * @return {Object}
  2070. */
  2071. static fromFormatExplain(text, fmt, options = {}) {
  2072. const { locale = null, numberingSystem = null } = options,
  2073. localeToUse = Locale.fromOpts({
  2074. locale,
  2075. numberingSystem,
  2076. defaultToEN: true,
  2077. });
  2078. return explainFromTokens(localeToUse, text, fmt);
  2079. }
  2080. /**
  2081. * @deprecated use fromFormatExplain instead
  2082. */
  2083. static fromStringExplain(text, fmt, options = {}) {
  2084. return DateTime.fromFormatExplain(text, fmt, options);
  2085. }
  2086. /**
  2087. * Build a parser for `fmt` using the given locale. This parser can be passed
  2088. * to {@link DateTime.fromFormatParser} to a parse a date in this format. This
  2089. * can be used to optimize cases where many dates need to be parsed in a
  2090. * specific format.
  2091. *
  2092. * @param {String} fmt - the format the string is expected to be in (see
  2093. * description)
  2094. * @param {Object} options - options used to set locale and numberingSystem
  2095. * for parser
  2096. * @returns {TokenParser} - opaque object to be used
  2097. */
  2098. static buildFormatParser(fmt, options = {}) {
  2099. const { locale = null, numberingSystem = null } = options,
  2100. localeToUse = Locale.fromOpts({
  2101. locale,
  2102. numberingSystem,
  2103. defaultToEN: true,
  2104. });
  2105. return new TokenParser(localeToUse, fmt);
  2106. }
  2107. /**
  2108. * Create a DateTime from an input string and format parser.
  2109. *
  2110. * The format parser must have been created with the same locale as this call.
  2111. *
  2112. * @param {String} text - the string to parse
  2113. * @param {TokenParser} formatParser - parser from {@link DateTime.buildFormatParser}
  2114. * @param {Object} opts - options taken by fromFormat()
  2115. * @returns {DateTime}
  2116. */
  2117. static fromFormatParser(text, formatParser, opts = {}) {
  2118. if (isUndefined(text) || isUndefined(formatParser)) {
  2119. throw new InvalidArgumentError(
  2120. "fromFormatParser requires an input string and a format parser"
  2121. );
  2122. }
  2123. const { locale = null, numberingSystem = null } = opts,
  2124. localeToUse = Locale.fromOpts({
  2125. locale,
  2126. numberingSystem,
  2127. defaultToEN: true,
  2128. });
  2129. if (!localeToUse.equals(formatParser.locale)) {
  2130. throw new InvalidArgumentError(
  2131. `fromFormatParser called with a locale of ${localeToUse}, ` +
  2132. `but the format parser was created for ${formatParser.locale}`
  2133. );
  2134. }
  2135. const { result, zone, specificOffset, invalidReason } = formatParser.explainFromTokens(text);
  2136. if (invalidReason) {
  2137. return DateTime.invalid(invalidReason);
  2138. } else {
  2139. return parseDataToDateTime(
  2140. result,
  2141. zone,
  2142. opts,
  2143. `format ${formatParser.format}`,
  2144. text,
  2145. specificOffset
  2146. );
  2147. }
  2148. }
  2149. // FORMAT PRESETS
  2150. /**
  2151. * {@link DateTime#toLocaleString} format like 10/14/1983
  2152. * @type {Object}
  2153. */
  2154. static get DATE_SHORT() {
  2155. return Formats.DATE_SHORT;
  2156. }
  2157. /**
  2158. * {@link DateTime#toLocaleString} format like 'Oct 14, 1983'
  2159. * @type {Object}
  2160. */
  2161. static get DATE_MED() {
  2162. return Formats.DATE_MED;
  2163. }
  2164. /**
  2165. * {@link DateTime#toLocaleString} format like 'Fri, Oct 14, 1983'
  2166. * @type {Object}
  2167. */
  2168. static get DATE_MED_WITH_WEEKDAY() {
  2169. return Formats.DATE_MED_WITH_WEEKDAY;
  2170. }
  2171. /**
  2172. * {@link DateTime#toLocaleString} format like 'October 14, 1983'
  2173. * @type {Object}
  2174. */
  2175. static get DATE_FULL() {
  2176. return Formats.DATE_FULL;
  2177. }
  2178. /**
  2179. * {@link DateTime#toLocaleString} format like 'Tuesday, October 14, 1983'
  2180. * @type {Object}
  2181. */
  2182. static get DATE_HUGE() {
  2183. return Formats.DATE_HUGE;
  2184. }
  2185. /**
  2186. * {@link DateTime#toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is.
  2187. * @type {Object}
  2188. */
  2189. static get TIME_SIMPLE() {
  2190. return Formats.TIME_SIMPLE;
  2191. }
  2192. /**
  2193. * {@link DateTime#toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is.
  2194. * @type {Object}
  2195. */
  2196. static get TIME_WITH_SECONDS() {
  2197. return Formats.TIME_WITH_SECONDS;
  2198. }
  2199. /**
  2200. * {@link DateTime#toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is.
  2201. * @type {Object}
  2202. */
  2203. static get TIME_WITH_SHORT_OFFSET() {
  2204. return Formats.TIME_WITH_SHORT_OFFSET;
  2205. }
  2206. /**
  2207. * {@link DateTime#toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is.
  2208. * @type {Object}
  2209. */
  2210. static get TIME_WITH_LONG_OFFSET() {
  2211. return Formats.TIME_WITH_LONG_OFFSET;
  2212. }
  2213. /**
  2214. * {@link DateTime#toLocaleString} format like '09:30', always 24-hour.
  2215. * @type {Object}
  2216. */
  2217. static get TIME_24_SIMPLE() {
  2218. return Formats.TIME_24_SIMPLE;
  2219. }
  2220. /**
  2221. * {@link DateTime#toLocaleString} format like '09:30:23', always 24-hour.
  2222. * @type {Object}
  2223. */
  2224. static get TIME_24_WITH_SECONDS() {
  2225. return Formats.TIME_24_WITH_SECONDS;
  2226. }
  2227. /**
  2228. * {@link DateTime#toLocaleString} format like '09:30:23 EDT', always 24-hour.
  2229. * @type {Object}
  2230. */
  2231. static get TIME_24_WITH_SHORT_OFFSET() {
  2232. return Formats.TIME_24_WITH_SHORT_OFFSET;
  2233. }
  2234. /**
  2235. * {@link DateTime#toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour.
  2236. * @type {Object}
  2237. */
  2238. static get TIME_24_WITH_LONG_OFFSET() {
  2239. return Formats.TIME_24_WITH_LONG_OFFSET;
  2240. }
  2241. /**
  2242. * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is.
  2243. * @type {Object}
  2244. */
  2245. static get DATETIME_SHORT() {
  2246. return Formats.DATETIME_SHORT;
  2247. }
  2248. /**
  2249. * {@link DateTime#toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is.
  2250. * @type {Object}
  2251. */
  2252. static get DATETIME_SHORT_WITH_SECONDS() {
  2253. return Formats.DATETIME_SHORT_WITH_SECONDS;
  2254. }
  2255. /**
  2256. * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is.
  2257. * @type {Object}
  2258. */
  2259. static get DATETIME_MED() {
  2260. return Formats.DATETIME_MED;
  2261. }
  2262. /**
  2263. * {@link DateTime#toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is.
  2264. * @type {Object}
  2265. */
  2266. static get DATETIME_MED_WITH_SECONDS() {
  2267. return Formats.DATETIME_MED_WITH_SECONDS;
  2268. }
  2269. /**
  2270. * {@link DateTime#toLocaleString} format like 'Fri, 14 Oct 1983, 9:30 AM'. Only 12-hour if the locale is.
  2271. * @type {Object}
  2272. */
  2273. static get DATETIME_MED_WITH_WEEKDAY() {
  2274. return Formats.DATETIME_MED_WITH_WEEKDAY;
  2275. }
  2276. /**
  2277. * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is.
  2278. * @type {Object}
  2279. */
  2280. static get DATETIME_FULL() {
  2281. return Formats.DATETIME_FULL;
  2282. }
  2283. /**
  2284. * {@link DateTime#toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is.
  2285. * @type {Object}
  2286. */
  2287. static get DATETIME_FULL_WITH_SECONDS() {
  2288. return Formats.DATETIME_FULL_WITH_SECONDS;
  2289. }
  2290. /**
  2291. * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is.
  2292. * @type {Object}
  2293. */
  2294. static get DATETIME_HUGE() {
  2295. return Formats.DATETIME_HUGE;
  2296. }
  2297. /**
  2298. * {@link DateTime#toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is.
  2299. * @type {Object}
  2300. */
  2301. static get DATETIME_HUGE_WITH_SECONDS() {
  2302. return Formats.DATETIME_HUGE_WITH_SECONDS;
  2303. }
  2304. }
  2305. /**
  2306. * @private
  2307. */
  2308. export function friendlyDateTime(dateTimeish) {
  2309. if (DateTime.isDateTime(dateTimeish)) {
  2310. return dateTimeish;
  2311. } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) {
  2312. return DateTime.fromJSDate(dateTimeish);
  2313. } else if (dateTimeish && typeof dateTimeish === "object") {
  2314. return DateTime.fromObject(dateTimeish);
  2315. } else {
  2316. throw new InvalidArgumentError(
  2317. `Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`
  2318. );
  2319. }
  2320. }