UNPKG

14 kBJavaScriptView Raw
1var Dayjs = (() => {
2 var __defProp = Object.defineProperty;
3 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4 var __getOwnPropNames = Object.getOwnPropertyNames;
5 var __hasOwnProp = Object.prototype.hasOwnProperty;
6 var __export = (target, all) => {
7 for (var name in all)
8 __defProp(target, name, { get: all[name], enumerable: true });
9 };
10 var __copyProps = (to, from, except, desc) => {
11 if (from && typeof from === "object" || typeof from === "function") {
12 for (let key of __getOwnPropNames(from))
13 if (!__hasOwnProp.call(to, key) && key !== except)
14 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15 }
16 return to;
17 };
18 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
20 // src/index.ts
21 var src_exports = {};
22 __export(src_exports, {
23 Dayjs: () => Dayjs,
24 dayjs: () => dayjs,
25 default: () => src_default,
26 extend: () => extend,
27 isDayjs: () => isDayjs,
28 locale: () => parseLocale,
29 unix: () => unix
30 });
31
32 // src/constants.ts
33 var SECONDS_A_MINUTE = 60;
34 var SECONDS_A_HOUR = SECONDS_A_MINUTE * 60;
35 var SECONDS_A_DAY = SECONDS_A_HOUR * 24;
36 var SECONDS_A_WEEK = SECONDS_A_DAY * 7;
37 var MILLISECONDS_A_SECOND = 1e3;
38 var MILLISECONDS_A_MINUTE = SECONDS_A_MINUTE * MILLISECONDS_A_SECOND;
39 var MILLISECONDS_A_HOUR = SECONDS_A_HOUR * MILLISECONDS_A_SECOND;
40 var MILLISECONDS_A_DAY = SECONDS_A_DAY * MILLISECONDS_A_SECOND;
41 var MILLISECONDS_A_WEEK = SECONDS_A_WEEK * MILLISECONDS_A_SECOND;
42 var INVALID_DATE_STRING = "Invalid Date";
43 var DEFAULT_FORMAT = "YYYY-MM-DDTHH:mm:ssZ";
44 var REGEX_PARSE = /^(\d{4})[/-]?(\d{1,2})?[/-]?(\d{0,2})[\sTt]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/;
45 var REGEX_FORMAT = /\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g;
46
47 // src/utils.ts
48 var mutable = (val) => val;
49 var pick = (object, keys) => keys.reduce((obj, key) => {
50 if (Object.prototype.hasOwnProperty.call(object, key))
51 obj[key] = object[key];
52 return obj;
53 }, {});
54 var cloneDate = (date) => new Date(date);
55 var padZoneStr = (utcOffset) => {
56 const negMinutes = -utcOffset;
57 const minutes = Math.abs(negMinutes);
58 const hourOffset = Math.floor(minutes / 60);
59 const minuteOffset = minutes % 60;
60 return `${negMinutes <= 0 ? "+" : "-"}${`${hourOffset}`.padStart(2, "0")}:${`${minuteOffset}`.padStart(2, "0")}`;
61 };
62 var isEmptyObject = (value) => typeof value === "object" && value !== null && Object.keys(value).length === 0;
63
64 // src/units.ts
65 var units = mutable({
66 y: "year",
67 M: "month",
68 D: "date",
69 h: "hour",
70 m: "minute",
71 s: "second",
72 ms: "millisecond",
73 d: "day",
74 w: "week"
75 });
76 var unitsShort = Object.keys(units);
77 var unitsLong = Object.values(units);
78 var isShortUnit = (unit) => unitsShort.includes(unit);
79 var normalize = (unit) => {
80 var _a, _b;
81 if (isShortUnit(unit)) {
82 return units[unit];
83 }
84 const normalizedUnit = (_b = (_a = unit == null ? void 0 : unit.toLowerCase()) == null ? void 0 : _a.replace(/s$/, "")) != null ? _b : "";
85 return normalizedUnit;
86 };
87
88 // src/locale/en.ts
89 var locale = {
90 name: "en",
91 weekdays: [
92 "Sunday",
93 "Monday",
94 "Tuesday",
95 "Wednesday",
96 "Thursday",
97 "Friday",
98 "Saturday"
99 ],
100 months: [
101 "January",
102 "February",
103 "March",
104 "April",
105 "May",
106 "June",
107 "July",
108 "August",
109 "September",
110 "October",
111 "November",
112 "December"
113 ]
114 };
115 var en_default = locale;
116
117 // src/dayjs.ts
118 var globalLocale = "en";
119 var loadedLocales = {};
120 loadedLocales[globalLocale] = en_default;
121 var parseDate = (date) => {
122 if (date instanceof Date)
123 return cloneDate(date);
124 else if (date === null)
125 return new Date(Number.NaN);
126 else if (date === void 0)
127 return new Date();
128 else if (isEmptyObject(date))
129 return new Date();
130 else if (Array.isArray(date))
131 return new Date(date[0], date[1], date[2], date[3], date[4], date[5], date[6]);
132 else if (typeof date === "string" && !/z$/i.test(date)) {
133 const d = date.match(REGEX_PARSE);
134 if (d) {
135 const m = +d[2] - 1 || 0;
136 const ms = +(d[7] || "0").slice(0, 3);
137 return new Date(+d[1], m, +(d[3] || 1), +(d[4] || 0), +(d[5] || 0), +(d[6] || 0), ms);
138 }
139 }
140 return new Date(date);
141 };
142 var parseLocale = (preset, isLocal, newLocale) => {
143 let locale2;
144 if (!preset) {
145 return globalLocale;
146 }
147 if (typeof preset === "string") {
148 const presetLower = preset.toLowerCase();
149 if (loadedLocales[presetLower]) {
150 locale2 = presetLower;
151 }
152 if (newLocale) {
153 loadedLocales[presetLower] = newLocale;
154 locale2 = presetLower;
155 }
156 const presetSplit = preset.split("-");
157 if (!locale2 && presetSplit.length > 1) {
158 return parseLocale(presetSplit[0]);
159 }
160 } else {
161 const { name } = preset;
162 loadedLocales[name] = preset;
163 locale2 = name;
164 }
165 if (!isLocal && locale2)
166 globalLocale = locale2;
167 return locale2 || (!isLocal ? globalLocale : "");
168 };
169 var Dayjs = class extends class {
170 } {
171 constructor(date, options) {
172 super();
173 this._d = new Date();
174 this._options = options || {};
175 this._locale = parseLocale(this._options.locale, true);
176 this.parse(date);
177 this._init();
178 }
179 parse(date) {
180 this._d = parseDate(date);
181 }
182 _init() {
183 this._year = this._d.getFullYear();
184 this._month = this._d.getMonth();
185 this._date = this._d.getDate();
186 this._hour = this._d.getHours();
187 this._minute = this._d.getMinutes();
188 this._second = this._d.getSeconds();
189 this._millisecond = this._d.getMilliseconds();
190 this._day = this._d.getDay();
191 }
192 valueOf() {
193 return this._d.getTime();
194 }
195 unix() {
196 return Math.floor(this.valueOf() / 1e3);
197 }
198 isValid() {
199 return !(this._d.toString() === INVALID_DATE_STRING);
200 }
201 _startEndOf(unit, isStartOf) {
202 const factory = ({
203 year = this._year,
204 month = this._month,
205 date = this._date,
206 hour = this._hour,
207 minute = this._minute,
208 second = this._second,
209 millisecond = this._millisecond
210 }) => new Dayjs([year, month, date, hour, minute, second, millisecond], this._options);
211 const numbers = isStartOf ? { month: 0, date: 1, hour: 0, minute: 0, second: 0, millisecond: 0 } : {
212 month: 11,
213 date: 31,
214 hour: 23,
215 minute: 59,
216 second: 59,
217 millisecond: 999
218 };
219 const normalizedUnit = normalize(unit);
220 switch (normalizedUnit) {
221 case "year":
222 return factory(numbers);
223 case "month":
224 return factory(isStartOf ? pick(numbers, ["date", "hour", "minute", "second", "millisecond"]) : {
225 month: this._month + 1,
226 date: 0,
227 ...pick(numbers, ["hour", "minute", "second", "millisecond"])
228 });
229 case "date":
230 case "day":
231 return factory(pick(numbers, ["hour", "minute", "second", "millisecond"]));
232 case "hour":
233 return factory(pick(numbers, ["minute", "second", "millisecond"]));
234 case "minute":
235 return factory(pick(numbers, ["second", "millisecond"]));
236 case "second":
237 return factory(pick(numbers, ["millisecond"]));
238 case "week": {
239 const weekStart = this.$locale().weekStart || 0;
240 const gap = (this._day < weekStart ? this._day + 7 : this._day) - weekStart;
241 return factory({
242 date: isStartOf ? this._date - gap : this._date + (6 - gap),
243 ...pick(numbers, ["hour", "minute", "second", "millisecond"])
244 });
245 }
246 case "millisecond":
247 return this.clone();
248 }
249 }
250 $locale() {
251 return loadedLocales[this._locale];
252 }
253 locale(preset, locale2) {
254 if (!preset)
255 return this._locale;
256 const that = this.clone();
257 const nextLocaleName = parseLocale(preset, true, locale2);
258 if (nextLocaleName)
259 that._locale = nextLocaleName;
260 return that;
261 }
262 startOf(unit) {
263 return this._startEndOf(unit, true);
264 }
265 endOf(unit) {
266 return this._startEndOf(unit, false);
267 }
268 isSame(that, unit = "millisecond") {
269 const other = dayjs(that);
270 return this.startOf(unit) <= other && other <= this.endOf(unit);
271 }
272 isAfter(that, unit = "millisecond") {
273 return dayjs(that) < this.startOf(unit);
274 }
275 isBefore(that, unit = "millisecond") {
276 return this.endOf(unit) < dayjs(that);
277 }
278 clone() {
279 return new Dayjs(this._d, this._options);
280 }
281 get(unit) {
282 return this[`_${unit}`];
283 }
284 set(unit, value) {
285 const methods = {
286 year: "setFullYear",
287 month: "setMonth",
288 date: "setDate",
289 hour: "setHours",
290 minute: "setMinutes",
291 second: "setSeconds",
292 millisecond: "setMilliseconds",
293 day: "setDate"
294 };
295 const method = methods[unit];
296 if (!method)
297 return this;
298 const date = cloneDate(this._d);
299 const val = unit === "day" ? this._date + (value - this._day) : value;
300 if (unit === "month" || unit === "year") {
301 date.setDate(1);
302 date[method](val);
303 date.setDate(Math.min(this._date, dayjs(date).daysInMonth()));
304 } else if (method)
305 date[method](val);
306 return dayjs(date);
307 }
308 daysInMonth() {
309 return this.endOf("month").date();
310 }
311 toDate() {
312 return cloneDate(this._d);
313 }
314 toJSON() {
315 return this.isValid() ? this.toISOString() : null;
316 }
317 toISOString() {
318 return this._d.toISOString();
319 }
320 toString() {
321 return this._d.toUTCString();
322 }
323 utcOffset() {
324 return -Math.round(this._d.getTimezoneOffset() / 15) * 15;
325 }
326 format(formatStr) {
327 const locale2 = this.$locale();
328 if (!this.isValid())
329 return locale2.invalidDate || INVALID_DATE_STRING;
330 const str = formatStr || DEFAULT_FORMAT;
331 const zoneStr = padZoneStr(this.utcOffset());
332 const { weekdays, months } = locale2;
333 const getShort = (arr, index, full, length) => (arr == null ? void 0 : arr[index]) || (full == null ? void 0 : full[index].slice(0, Math.max(0, length != null ? length : 0)));
334 const getHour = (num) => `${this._hour % 12 || 12}`.padStart(num, "0");
335 const meridiem = locale2.meridiem || ((hour, minute, isLowercase) => {
336 const m = hour < 12 ? "AM" : "PM";
337 return isLowercase ? m.toLowerCase() : m;
338 });
339 const matches = {
340 YY: String(this._year).slice(-2),
341 YYYY: this._year,
342 M: this._month + 1,
343 MM: `${this._month + 1}`.padStart(2, "0"),
344 MMM: getShort(locale2.monthsShort, this._month, months, 3),
345 MMMM: getShort(months, this._month),
346 D: this._date,
347 DD: `${this._date}`.padStart(2, "0"),
348 d: String(this._day),
349 dd: getShort(locale2.weekdaysMin, this._day, weekdays, 2),
350 ddd: getShort(locale2.weekdaysShort, this._day, weekdays, 3),
351 dddd: weekdays[this._day],
352 H: String(this._hour),
353 HH: `${this._hour}`.padStart(2, "0"),
354 h: getHour(1),
355 hh: getHour(2),
356 a: meridiem(this._hour, this._minute, true),
357 A: meridiem(this._hour, this._minute, false),
358 m: String(this._minute),
359 mm: `${this._minute}`.padStart(2, "0"),
360 s: String(this._second),
361 ss: `${this._second}`.padStart(2, "0"),
362 SSS: `${this._millisecond}`.padStart(3, "0"),
363 Z: zoneStr
364 };
365 return str.replace(REGEX_FORMAT, (match, $1) => $1 || matches[match] || zoneStr.replace(":", ""));
366 }
367 add(number, unit) {
368 const normalizedUnit = normalize(unit);
369 const factory = (n) => this.date(this.date() + Math.round(n * number));
370 if (normalizedUnit === "month") {
371 return this.set("month", this._month + number);
372 } else if (normalizedUnit === "year") {
373 return this.set("year", this._year + number);
374 } else if (normalizedUnit === "day") {
375 return factory(1);
376 } else if (normalizedUnit === "week") {
377 return factory(7);
378 }
379 const steps = {
380 minute: MILLISECONDS_A_MINUTE,
381 hour: MILLISECONDS_A_HOUR,
382 second: MILLISECONDS_A_SECOND,
383 millisecond: 1
384 };
385 const step = steps[normalizedUnit];
386 const nextTimeStamp = this.valueOf() + number * step;
387 return new Dayjs(nextTimeStamp, this._options);
388 }
389 subtract(number, unit) {
390 return this.add(number * -1, unit);
391 }
392 };
393 var getterOrSetter = (unit) => {
394 function fn(value) {
395 if (value === void 0) {
396 return this.get(unit);
397 } else {
398 return this.set(unit, value);
399 }
400 }
401 return fn;
402 };
403 [
404 "year",
405 "month",
406 "date",
407 "hour",
408 "minute",
409 "second",
410 "millisecond",
411 "day"
412 ].forEach((unit) => Dayjs.prototype[unit] = getterOrSetter(unit));
413 var isDayjs = (value) => value instanceof Dayjs;
414 var unix = (timestamp) => dayjs(timestamp * 1e3);
415 var extend = (plugin, option) => {
416 if (!plugin._i) {
417 plugin(Dayjs, dayjs, option);
418 plugin._i = true;
419 }
420 return dayjs;
421 };
422 var dayjs = (date, format, locale2, strict) => {
423 if (isDayjs(date))
424 return date;
425 if (typeof locale2 === "boolean") {
426 strict = locale2;
427 locale2 = void 0;
428 }
429 const options = {
430 format,
431 locale: locale2,
432 strict
433 };
434 return new Dayjs(date, options);
435 };
436 dayjs.isDayjs = isDayjs;
437 dayjs.unix = unix;
438 dayjs.extend = extend;
439 dayjs.locale = parseLocale;
440
441 // src/index.ts
442 var src_default = dayjs;
443 return __toCommonJS(src_exports);
444})();