Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

datetime.js 78KB

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