@quenty/time 2.5.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,41 +1,74 @@
1
1
  --!strict
2
2
  --[=[
3
- Library handles time based parsing / operations. Untested. Based off of PHP's time system.
4
-
5
- :::note
6
- This library is out of date, and does not necessarily work. I recommend using os.time()
7
- :::
8
-
9
3
  @class Time
10
4
  ]=]
11
5
 
6
+ local require = require(script.Parent.loader).load(script)
7
+
8
+ local NumberLocalizationOrdinalUtils = require("NumberLocalizationOrdinalUtils")
9
+
12
10
  local Time = {}
13
11
 
14
- -- luacheck: push ignore 631
15
- local MONTH_NAMES = {
16
- "January",
17
- "February",
18
- "March",
19
- "April",
20
- "May",
21
- "June",
22
- "July",
23
- "August",
24
- "September",
25
- "October",
26
- "November",
27
- "December",
12
+ --[=[
13
+ A unix timestamp in seconds (fractions are floored), a Roblox `DateTime`, an ISO 8601 string
14
+ such as `"2025-09-22T13:00:00Z"`, or `nil` for the current time.
15
+
16
+ @type DateTimeLike number | DateTime | string | nil
17
+ @within Time
18
+ ]=]
19
+ export type DateTimeLike = (number | DateTime | string)?
20
+
21
+ type UniversalTime = {
22
+ Year: number,
23
+ Month: number,
24
+ Day: number,
25
+ Hour: number,
26
+ Minute: number,
27
+ Second: number,
28
+ Millisecond: number,
28
29
  }
29
- local MONTH_NAMES_SHORT = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
30
- local DAYS_IN_MONTH = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
31
- local DAYS_OF_WEEK = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }
32
- local DAYS_OF_WEEK_SHORT = { "Sun", "Mon", "Tues", "Weds", "Thurs", "Fri", "Sat" }
33
- -- luacheck: pop
30
+
31
+ -- Roblox has no default locale: FormatUniversalTime errors without one and falls back to English
32
+ -- (with a warning) for one it does not know.
33
+ local DEFAULT_LOCALE = "en-us"
34
+
35
+ local DAYS_IN_MONTH = table.freeze({ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 })
36
+ local SECONDS_PER_DAY = 86400
37
+ local UNIX_EPOCH_JULIAN_DAY = 2440588
38
+
39
+ function Time._toDateTime(currentTime: DateTimeLike): DateTime
40
+ if currentTime == nil then
41
+ return DateTime.now()
42
+ elseif typeof(currentTime) == "DateTime" then
43
+ return currentTime
44
+ elseif type(currentTime) == "number" then
45
+ return DateTime.fromUnixTimestamp(math.floor(currentTime))
46
+ elseif type(currentTime) == "string" then
47
+ local dateTime = DateTime.fromIsoDate(currentTime)
48
+ assert(dateTime, "Bad ISO date")
49
+ return dateTime
50
+ else
51
+ error(string.format("Bad currentTime %q", typeof(currentTime)))
52
+ end
53
+ end
54
+
55
+ function Time._toUniversalTime(currentTime: DateTimeLike): UniversalTime
56
+ -- The engine definitions type ToUniversalTime() as { any }
57
+ return Time._toDateTime(currentTime):ToUniversalTime() :: any
58
+ end
59
+
60
+ function Time._formatUniversal(currentTime: DateTimeLike, format: string, locale: string?): string
61
+ return Time._toDateTime(currentTime):FormatUniversalTime(format, locale or DEFAULT_LOCALE)
62
+ end
63
+
64
+ function Time._formatUniversalNumber(currentTime: DateTimeLike, format: string): number
65
+ local value = tonumber(Time._formatUniversal(currentTime, format))
66
+ assert(value, "Failed to parse formatted time")
67
+ return value
68
+ end
34
69
 
35
70
  --[=[
36
71
  Returns a Days in months table for the given year
37
- @param year number
38
- @return { [number]: number }
39
72
  ]=]
40
73
  function Time.getDaysMonthTable(year: number): { [number]: number }
41
74
  local copy = table.clone(DAYS_IN_MONTH)
@@ -46,483 +79,762 @@ function Time.getDaysMonthTable(year: number): { [number]: number }
46
79
  copy[2] = 28
47
80
  end
48
81
 
49
- return copy
82
+ return table.freeze(copy)
50
83
  end
51
84
 
52
85
  --[=[
53
86
  Returns the second of the given time.
54
- @param currentTime number
55
- @return number
56
87
  ]=]
57
- function Time.getSecond(currentTime: number): number
58
- return math.floor(currentTime % 60)
88
+ function Time.getSecond(currentTime: DateTimeLike): number
89
+ return Time._toUniversalTime(currentTime).Second
59
90
  end
60
91
 
61
92
  --[=[
62
93
  Returns the minute of the given time.
63
- @param currentTime number
64
- @return number
65
94
  ]=]
66
- function Time.getMinute(currentTime: number): number
67
- return math.floor(currentTime / 60 % 60)
95
+ function Time.getMinute(currentTime: DateTimeLike): number
96
+ return Time._toUniversalTime(currentTime).Minute
68
97
  end
69
98
 
70
99
  --[=[
71
100
  Returns the hour of the given time in 24-hour format.
72
- @param currentTime number
73
- @return number
74
101
  ]=]
75
- function Time.getHour(currentTime: number): number
76
- return math.floor(currentTime / 3600 % 24)
102
+ function Time.getHour(currentTime: DateTimeLike): number
103
+ return Time._toUniversalTime(currentTime).Hour
77
104
  end
78
105
 
79
106
  --[=[
80
- Returns the day of the year for the given time.
81
- @param currentTime number
82
- @return number
107
+ Returns the day of the year (1-366) for the given time.
83
108
  ]=]
84
- function Time.getDay(currentTime: number): number
85
- return math.ceil(currentTime / 60 / 60 / 24 % 365.25)
109
+ function Time.getDay(currentTime: DateTimeLike): number
110
+ return Time._formatUniversalNumber(currentTime, "DDD")
86
111
  end
87
112
 
88
113
  --[=[
89
114
  Returns the year for the given time.
90
- @param currentTime number
91
- @return number
92
115
  ]=]
93
- function Time.getYear(currentTime: number): number
94
- return math.floor(currentTime / 60 / 60 / 24 / 365.25 + 1970)
116
+ function Time.getYear(currentTime: DateTimeLike): number
117
+ return Time._toUniversalTime(currentTime).Year
95
118
  end
96
119
 
97
120
  --[=[
98
121
  Returns the last two digits of the year for the given time.
99
- @param currentTime number
100
- @return number
101
122
  ]=]
102
- function Time.getYearShort(currentTime: number): number
123
+ function Time.getYearShort(currentTime: DateTimeLike): number
103
124
  return Time.getYear(currentTime) % 100
104
125
  end
105
126
 
106
127
  --[=[
107
128
  Returns the last two digits of the year formatted as a string.
108
- @param currentTime number
109
- @return string
110
129
  ]=]
111
- function Time.getYearShortFormatted(currentTime: number): string
112
- local shortYear = Time.getYearShort(currentTime)
113
- if shortYear < 10 then
114
- return "0" .. shortYear
115
- end
116
- return tostring(shortYear)
130
+ function Time.getYearShortFormatted(currentTime: DateTimeLike, locale: string?): string
131
+ return Time._formatUniversal(currentTime, "YY", locale)
117
132
  end
118
133
 
119
134
  --[=[
120
- Returns the month of the given time.
121
- @param currentTime number
122
- @return number?
135
+ Returns the month (1-12) of the given time.
123
136
  ]=]
124
- function Time.getMonth(currentTime: number): number?
125
- local year = Time.getYear(currentTime)
126
- local day = Time.getDay(currentTime)
127
-
128
- local daysInMonth = Time.getDaysMonthTable(year)
129
-
130
- for i = 1, #daysInMonth do
131
- if day > daysInMonth[i] then
132
- day = day - daysInMonth[i]
133
- else
134
- return i
135
- end
136
- end
137
-
138
- return nil
137
+ function Time.getMonth(currentTime: DateTimeLike): number
138
+ return Time._toUniversalTime(currentTime).Month
139
139
  end
140
140
 
141
141
  --[=[
142
142
  Returns the month formatted as a two-digit string.
143
- @param currentTime number
144
- @return string
145
143
  ]=]
146
- function Time.getFormattedMonth(currentTime: number): string
147
- local month = assert(Time.getMonth(currentTime), "Failed to get month")
148
- if month < 10 then
149
- return "0" .. month
150
- end
151
-
152
- return tostring(month)
144
+ function Time.getFormattedMonth(currentTime: DateTimeLike, locale: string?): string
145
+ return Time._formatUniversal(currentTime, "MM", locale)
153
146
  end
154
147
 
155
148
  --[=[
156
- Returns the day of the month for the given time.
157
- @param currentTime number
158
- @return number?
149
+ Returns the day of the month (1-31) for the given time.
159
150
  ]=]
160
- function Time.getDayOfTheMonth(currentTime: number): number?
161
- local year = Time.getYear(currentTime)
162
- local day = Time.getDay(currentTime)
163
-
164
- local daysInMonth = Time.getDaysMonthTable(year)
165
-
166
- for i = 1, #daysInMonth do
167
- if day > daysInMonth[i] then
168
- day = day - daysInMonth[i]
169
- else
170
- return day
171
- end
172
- end
173
-
174
- return nil
151
+ function Time.getDayOfTheMonth(currentTime: DateTimeLike): number
152
+ return Time._toUniversalTime(currentTime).Day
175
153
  end
176
154
 
177
155
  --[=[
178
156
  Returns the day of the month formatted as a two-digit string.
179
- @param currentTime number
180
- @return string
181
157
  ]=]
182
- function Time.getFormattedDayOfTheMonth(currentTime: number): string
183
- local dayOfTheMonth = assert(Time.getDayOfTheMonth(currentTime), "Failed to get day of the month")
184
-
185
- if dayOfTheMonth < 10 then
186
- return "0" .. dayOfTheMonth
187
- end
188
-
189
- return tostring(dayOfTheMonth)
158
+ function Time.getFormattedDayOfTheMonth(currentTime: DateTimeLike, locale: string?): string
159
+ return Time._formatUniversal(currentTime, "DD", locale)
190
160
  end
191
161
 
192
162
  --[=[
193
163
  Returns the full name of the month for the given time.
194
- @param currentTime number
195
- @return string
196
164
  ]=]
197
- function Time.getMonthName(currentTime: number): string
198
- local month = Time.getMonth(currentTime)
199
- if month == nil then
200
- return "Unknown"
201
- end
202
-
203
- return MONTH_NAMES[month]
165
+ function Time.getMonthName(currentTime: DateTimeLike, locale: string?): string
166
+ return Time._formatUniversal(currentTime, "MMMM", locale)
204
167
  end
205
168
 
206
169
  --[=[
207
170
  Returns the abbreviated name of the month for the given time.
208
- @param currentTime number
209
- @return string
210
171
  ]=]
211
- function Time.getMonthNameShort(currentTime: number): string
212
- local month = Time.getMonth(currentTime)
213
- if month == nil then
214
- return "???"
215
- end
216
-
217
- return MONTH_NAMES_SHORT[month]
172
+ function Time.getMonthNameShort(currentTime: DateTimeLike, locale: string?): string
173
+ return Time._formatUniversal(currentTime, "MMM", locale)
218
174
  end
219
175
 
220
176
  --[=[
221
- Calculates the Julian date for the given time.
222
- @param currentTime number
223
- @return number
177
+ Returns the Julian day number for the given time.
224
178
  ]=]
225
- function Time.getJulianDate(currentTime: number): number
226
- local month = assert(Time.getMonth(currentTime), "Failed to get month")
227
- local year = Time.getYear(currentTime)
228
- local day = Time.getDay(currentTime)
229
-
230
- local a = (14 - month) / 12
231
- local y = year + 4800 - a
232
- local m = month + 12 * a - 3
233
-
234
- local julianDay = day + ((153 * m + 2) / 5) + 365 * y + (y / 4) - (y / 100) + (y / 400) - 32045
235
-
236
- --[[local julianDay = (day
237
- + ((153 * (month + 12 * ((14 - month) / 12 ) - 3) + 2) / 5)
238
- + (365 * (year + 4800 - ((14 - month) / 12)))
239
- + ((year + 4800 - ((14 - month) / 12)) / 4)
240
- + ((year + 4800 - ((14 - month) / 12)) / 100)
241
- + ((year + 4800 - ((14 - month) / 12)) / 400)
242
- - 32045)--]]
243
-
244
- return julianDay
179
+ function Time.getJulianDate(currentTime: DateTimeLike): number
180
+ return Time._toDateTime(currentTime).UnixTimestamp // SECONDS_PER_DAY + UNIX_EPOCH_JULIAN_DAY
245
181
  end
246
182
 
247
183
  --[=[
248
- Returns the day of the week as a number (0-6) for the given time.
249
- @param currentTime number
250
- @return number
184
+ Returns the day of the week as a number (0-6, starting on Sunday) for the given time.
251
185
  ]=]
252
- function Time.getDayOfTheWeek(currentTime: number): number
253
- return math.floor(Time.getJulianDate(currentTime)) % 7
186
+ function Time.getDayOfTheWeek(currentTime: DateTimeLike): number
187
+ return Time._formatUniversalNumber(currentTime, "d")
254
188
  end
255
189
 
256
190
  --[=[
257
191
  Returns the full name of the day of the week for the given time.
258
- @param currentTime number
259
- @return string
260
192
  ]=]
261
- function Time.getDayOfTheWeekName(currentTime: number): string
262
- return DAYS_OF_WEEK[Time.getDayOfTheWeek(currentTime)]
193
+ function Time.getDayOfTheWeekName(currentTime: DateTimeLike, locale: string?): string
194
+ return Time._formatUniversal(currentTime, "dddd", locale)
263
195
  end
264
196
 
265
197
  --[=[
266
198
  Returns the abbreviated name of the day of the week for the given time.
267
- @param currentTime number
268
- @return string
269
199
  ]=]
270
- function Time.getDayOfTheWeekNameShort(currentTime: number): string
271
- return DAYS_OF_WEEK_SHORT[Time.getDayOfTheWeek(currentTime)]
200
+ function Time.getDayOfTheWeekNameShort(currentTime: DateTimeLike, locale: string?): string
201
+ return Time._formatUniversal(currentTime, "ddd", locale)
272
202
  end
273
203
 
274
204
  --[=[
275
- Returns the ordinal suffix (e.g., "st", "nd", "rd", "th") for a given number.
276
- @param number number
277
- @return string
205
+ Returns the localized ordinal suffix for a number, for example `nd` for 22 in English.
206
+ See [NumberLocalizationOrdinalUtils.getSuffix].
278
207
  ]=]
279
- function Time.getOrdinalOfNumber(number: number): string
280
- local tenRemainder = number % 10
281
- local hundredRemainder = number % 100
282
-
283
- if hundredRemainder >= 10 and hundredRemainder <= 20 then
284
- return "th"
285
- end
286
-
287
- if tenRemainder == 1 then
288
- return "st"
289
- elseif tenRemainder == 2 then
290
- return "nd"
291
- elseif tenRemainder == 3 then
292
- return "rd"
293
- else
294
- return "th"
295
- end
208
+ function Time.getOrdinalOfNumber(number: number, locale: string?): string
209
+ return NumberLocalizationOrdinalUtils.getSuffix(number, locale or DEFAULT_LOCALE)
296
210
  end
297
211
 
298
212
  --[=[
299
- Returns the ordinal suffix for the day of the month for the given time.
300
- @param currentTime number
301
- @return string?
213
+ Returns the localized ordinal suffix for the day of the month for the given time.
302
214
  ]=]
303
- function Time.getDayOfTheMonthOrdinal(currentTime: number): string?
304
- local dayOfMonth = Time.getDayOfTheMonth(currentTime)
305
- if dayOfMonth == nil then
306
- return nil
307
- end
308
-
309
- return Time.getOrdinalOfNumber(dayOfMonth)
215
+ function Time.getDayOfTheMonthOrdinal(currentTime: DateTimeLike, locale: string?): string
216
+ return Time.getOrdinalOfNumber(Time.getDayOfTheMonth(currentTime), locale)
310
217
  end
311
218
 
312
219
  --[=[
313
220
  Returns the second formatted as a two-digit string.
314
- @param currentTime number
315
- @return string
316
221
  ]=]
317
- function Time.getFormattedSecond(currentTime: number): string
318
- local currentSecond = Time.getSecond(currentTime)
319
- if currentSecond < 10 then
320
- return "0" .. currentSecond
321
- end
322
- return tostring(currentSecond)
222
+ function Time.getFormattedSecond(currentTime: DateTimeLike, locale: string?): string
223
+ return Time._formatUniversal(currentTime, "ss", locale)
323
224
  end
324
225
 
325
226
  --[=[
326
227
  Returns the minute formatted as a two-digit string.
327
- @param currentTime number
328
- @return string
329
228
  ]=]
330
- function Time.getFormattedMinute(currentTime: number): string
331
- local currentMinute = Time.getMinute(currentTime)
332
- if currentMinute < 10 then
333
- return "0" .. currentMinute
334
- end
335
- return tostring(currentMinute)
229
+ function Time.getFormattedMinute(currentTime: DateTimeLike, locale: string?): string
230
+ return Time._formatUniversal(currentTime, "mm", locale)
336
231
  end
337
232
 
338
233
  --[=[
339
- Returns the hour in 12-hour format.
340
- @param currentTime number
341
- @return number
234
+ Returns the hour in 12-hour format (1-12).
342
235
  ]=]
343
- function Time.getRegularHour(currentTime: number): number
344
- local hour = Time.getHour(currentTime)
345
- if hour > 12 then
346
- hour = hour - 12
347
- end
348
- return hour
236
+ function Time.getRegularHour(currentTime: DateTimeLike): number
237
+ return Time._formatUniversalNumber(currentTime, "h")
349
238
  end
350
239
 
351
240
  --[=[
352
241
  Returns the hour formatted as a two-digit string in 24-hour format.
353
- @param currentTime number
354
- @return string
355
242
  ]=]
356
- function Time.getHourFormatted(currentTime: number): string
357
- local hour = Time.getHour(currentTime)
358
- if hour < 10 then
359
- return "0" .. hour
360
- end
361
- return tostring(hour)
243
+ function Time.getHourFormatted(currentTime: DateTimeLike, locale: string?): string
244
+ return Time._formatUniversal(currentTime, "HH", locale)
362
245
  end
363
246
 
364
247
  --[=[
365
248
  Returns the hour formatted as a two-digit string in 12-hour format.
366
- @param currentTime number
367
- @return string
368
249
  ]=]
369
- function Time.getRegularHourFormatted(currentTime: number): string
370
- local hour = Time.getRegularHour(currentTime)
371
- if hour < 10 then
372
- return "0" .. hour
373
- end
374
- return tostring(hour)
250
+ function Time.getRegularHourFormatted(currentTime: DateTimeLike, locale: string?): string
251
+ return Time._formatUniversal(currentTime, "hh", locale)
375
252
  end
376
253
 
377
254
  --[=[
378
- Returns "am" or "pm" based on the given time.
379
- @param currentTime number
380
- @return "am" | "pm"
255
+ Returns "am" or "pm" (or the locale's equivalent) based on the given time.
381
256
  ]=]
382
- function Time.getamOrpm(currentTime: number): "am" | "pm"
383
- local hour = Time.getHour(currentTime)
384
-
385
- if hour > 12 then
386
- return "pm"
387
- else
388
- return "am"
389
- end
257
+ function Time.getamOrpm(currentTime: DateTimeLike, locale: string?): string
258
+ return Time._formatUniversal(currentTime, "a", locale)
390
259
  end
391
260
 
392
261
  --[=[
393
- Returns "AM" or "PM" based on the given time.
394
- @param currentTime number
395
- @return "AM" | "PM"
262
+ Returns "AM" or "PM" (or the locale's equivalent) based on the given time.
396
263
  ]=]
397
- function Time.getAMorPM(currentTime: number): "AM" | "PM"
398
- local hour = Time.getHour(currentTime)
399
-
400
- if hour > 12 then
401
- return "PM"
402
- else
403
- return "AM"
404
- end
264
+ function Time.getAMorPM(currentTime: DateTimeLike, locale: string?): string
265
+ return Time._formatUniversal(currentTime, "A", locale)
405
266
  end
406
267
 
407
268
  --[=[
408
269
  Reports the time in 24-hour format as a two-digit string.
409
- @param currentTime number
410
- @return string
411
270
  ]=]
412
- function Time.getMilitaryHour(currentTime: number): string
413
- local hour = Time.getHour(currentTime)
414
- if hour < 10 then
415
- return "0" .. hour
416
- end
417
- return tostring(hour)
271
+ function Time.getMilitaryHour(currentTime: DateTimeLike, locale: string?): string
272
+ return Time.getHourFormatted(currentTime, locale)
418
273
  end
419
274
 
420
275
  --[=[
421
276
  Determines if the year of the given time is a leap year.
422
- @param currentTime number
423
- @return boolean
424
277
  ]=]
425
- function Time.isLeapYear(currentTime: number): boolean
278
+ function Time.isLeapYear(currentTime: DateTimeLike): boolean
426
279
  local year = Time.getYear(currentTime)
427
- if year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0) then
428
- return true
429
- else
430
- return false
431
- end
280
+ return year % 4 == 0 and (year % 100 ~= 0 or year % 400 == 0)
432
281
  end
433
282
 
434
283
  --[=[
435
284
  Returns the number of days in the month for the given time.
436
- @param currentTime number
437
- @return number
438
285
  ]=]
439
- function Time.getDaysInMonth(currentTime: number): number
440
- local month = assert(Time.getMonth(currentTime), "Failed to get month")
441
- local year = Time.getYear(currentTime)
442
- return Time.getDaysMonthTable(year)[month]
443
- end
444
-
445
- local ISO_FORMAT_STRINGS: { [string]: (number) -> any } = {
446
- d = Time.getFormattedDayOfTheMonth,
447
- D = Time.getDayOfTheWeekNameShort,
448
- j = Time.getDayOfTheMonth,
449
- l = Time.getDayOfTheWeekName,
450
- N = Time.getDayOfTheWeek,
451
- S = Time.getDayOfTheMonthOrdinal,
452
- W = Time.getDayOfTheWeek,
453
- Z = Time.getDay,
454
-
455
- -- W
456
-
457
- F = Time.getMonthName,
458
- m = Time.getFormattedMonth,
459
- M = Time.getMonthNameShort,
460
- n = Time.getMonth,
461
- t = Time.getDaysInMonth,
462
-
463
- L = Time.isLeapYear,
464
- o = Time.getYear,
465
- Y = Time.getYear, -- Screw ISO-8610, it confuses me.
466
- y = Time.getYearShortFormatted,
467
-
468
- a = Time.getamOrpm,
469
- A = Time.getAMorPM,
470
- --B -- No one uses it
471
- g = Time.getRegularHour,
472
- G = Time.getHour,
473
- h = Time.getRegularHourFormatted,
474
- H = Time.getHourFormatted,
475
- i = Time.getFormattedMinute,
476
- s = Time.getFormattedSecond,
477
-
478
- X = Time.getJulianDate, -- For testing purposes.
479
-
480
- -- e -- No way to get Time Zones
481
- -- I -- Daylight saving time should be added later.
482
- -- O -- No way to get Time Zones
483
- -- P -- No way to get Time Zones
484
- -- T -- No way to get Time Zones
485
- -- Z -- No way to get Time Zones
486
-
487
- -- c -- ISO 8601
488
- -- r -- No need for formatted dates
489
- U = time,
286
+ function Time.getDaysInMonth(currentTime: DateTimeLike): number
287
+ local universalTime = Time._toUniversalTime(currentTime)
288
+ return Time.getDaysMonthTable(universalTime.Year)[universalTime.Month]
289
+ end
290
+
291
+ --[=[
292
+ Returns the unix timestamp in seconds for the given time.
293
+ ]=]
294
+ function Time.getUnixTimestamp(currentTime: DateTimeLike): number
295
+ return Time._toDateTime(currentTime).UnixTimestamp
296
+ end
297
+
298
+ --[=[
299
+ A unit of time for [Time.add], [Time.subtract], [Time.startOf] and [Time.endOf], singular or
300
+ plural, or one of the shorthands `ms`, `s`, `m`, `h`, `d`, `D`, `w`, `M`, `Q` and `y`.
301
+ `date` is another name for `day`.
302
+
303
+ @type TimeUnit "millisecond" | "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year" | plurals | shorthands
304
+ @within Time
305
+ ]=]
306
+ export type TimeUnit =
307
+ "millisecond"
308
+ | "milliseconds"
309
+ | "ms"
310
+ | "second"
311
+ | "seconds"
312
+ | "s"
313
+ | "minute"
314
+ | "minutes"
315
+ | "m"
316
+ | "hour"
317
+ | "hours"
318
+ | "h"
319
+ | "day"
320
+ | "days"
321
+ | "d"
322
+ | "date"
323
+ | "D"
324
+ | "week"
325
+ | "weeks"
326
+ | "w"
327
+ | "month"
328
+ | "months"
329
+ | "M"
330
+ | "quarter"
331
+ | "quarters"
332
+ | "Q"
333
+ | "year"
334
+ | "years"
335
+ | "y"
336
+
337
+ type CanonicalTimeUnit = "millisecond" | "second" | "minute" | "hour" | "day" | "week" | "month" | "quarter" | "year"
338
+
339
+ local TIME_UNIT_ALIASES: { [string]: CanonicalTimeUnit } = {
340
+ millisecond = "millisecond",
341
+ milliseconds = "millisecond",
342
+ ms = "millisecond",
343
+ second = "second",
344
+ seconds = "second",
345
+ s = "second",
346
+ minute = "minute",
347
+ minutes = "minute",
348
+ m = "minute",
349
+ hour = "hour",
350
+ hours = "hour",
351
+ h = "hour",
352
+ day = "day",
353
+ days = "day",
354
+ d = "day",
355
+ date = "day",
356
+ D = "day",
357
+ week = "week",
358
+ weeks = "week",
359
+ w = "week",
360
+ month = "month",
361
+ months = "month",
362
+ M = "month",
363
+ quarter = "quarter",
364
+ quarters = "quarter",
365
+ Q = "quarter",
366
+ year = "year",
367
+ years = "year",
368
+ y = "year",
490
369
  }
491
370
 
492
- local matchString: string = "["
493
- do
494
- for i, _ in ISO_FORMAT_STRINGS do
495
- matchString ..= i
371
+ -- Units that are a fixed number of milliseconds. Month, quarter and year move on the calendar.
372
+ local TIME_UNIT_MILLISECONDS: { [string]: number } = {
373
+ millisecond = 1,
374
+ second = 1000,
375
+ minute = 60000,
376
+ hour = 3600000,
377
+ day = 86400000,
378
+ week = 604800000,
379
+ }
380
+
381
+ function Time._normalizeUnit(unit: TimeUnit): CanonicalTimeUnit
382
+ local normalized = TIME_UNIT_ALIASES[unit]
383
+ assert(normalized, string.format("Bad unit %q", tostring(unit)))
384
+ return normalized :: CanonicalTimeUnit
385
+ end
386
+
387
+ -- Moves whole months on the calendar, clamping the day to the target month
388
+ function Time._addMonths(dateTime: DateTime, months: number): DateTime
389
+ local universalTime = Time._toUniversalTime(dateTime)
390
+ local monthIndex = universalTime.Month - 1 + months
391
+ local year = universalTime.Year + monthIndex // 12
392
+ local month = monthIndex % 12 + 1
393
+ local day = math.min(universalTime.Day, Time.getDaysMonthTable(year)[month])
394
+
395
+ return DateTime.fromUniversalTime(
396
+ year,
397
+ month,
398
+ day,
399
+ universalTime.Hour,
400
+ universalTime.Minute,
401
+ universalTime.Second,
402
+ universalTime.Millisecond
403
+ )
404
+ end
405
+
406
+ --[=[
407
+ Returns a `DateTime` moved forward by `value` units. Months, quarters and
408
+ years move on the calendar and clamp the day, so January 31st plus a month is February 28th
409
+ (or 29th); every other unit is a fixed offset. A negative value moves backwards.
410
+
411
+ ```lua
412
+ Time.add("2025-01-31T00:00:00Z", 1, "month") --> 2025-02-28T00:00:00Z
413
+ Time.add(os.time(), 7, "days")
414
+ ```
415
+ ]=]
416
+ function Time.add(currentTime: DateTimeLike, value: number, unit: TimeUnit): DateTime
417
+ assert(type(value) == "number", "Bad value")
418
+
419
+ local dateTime = Time._toDateTime(currentTime)
420
+ local normalized = Time._normalizeUnit(unit)
421
+
422
+ local monthsPerUnit = if normalized == "month"
423
+ then 1
424
+ elseif normalized == "quarter" then 3
425
+ elseif normalized == "year" then 12
426
+ else nil
427
+ if monthsPerUnit then
428
+ local wholeMonths = math.modf(value * monthsPerUnit)
429
+ return Time._addMonths(dateTime, wholeMonths)
496
430
  end
497
- matchString ..= "]"
431
+
432
+ return DateTime.fromUnixTimestampMillis(dateTime.UnixTimestampMillis + value * TIME_UNIT_MILLISECONDS[normalized])
498
433
  end
499
434
 
500
435
  --[=[
501
- Formats the given time based on the provided format string.
502
- @param format string
503
- @param currentTime number?
504
- @return string
436
+ Returns a `DateTime` moved back by `value` units. See [Time.add].
505
437
  ]=]
506
- function Time.getFormattedTime(format: string, currentTime: number?): string
507
- local resolvedTime = currentTime or tick()
438
+ function Time.subtract(currentTime: DateTimeLike, value: number, unit: TimeUnit): DateTime
439
+ assert(type(value) == "number", "Bad value")
440
+
441
+ return Time.add(currentTime, -value, unit)
442
+ end
508
443
 
509
- local returnString = format
510
- local formatsRequired: { string } = {}
444
+ --[=[
445
+ Returns a `DateTime` at the first instant of the unit containing `currentTime`:
446
+ `startOf(t, "day")` is midnight, `startOf(t, "month")` the 1st at midnight. Weeks
447
+ start on Sunday.
448
+
449
+ ```lua
450
+ Time.startOf("2025-09-22T13:45:30Z", "week") --> 2025-09-21T00:00:00Z
451
+ ```
452
+ ]=]
453
+ function Time.startOf(currentTime: DateTimeLike, unit: TimeUnit): DateTime
454
+ local dateTime = Time._toDateTime(currentTime)
455
+ local normalized = Time._normalizeUnit(unit)
456
+ local t = Time._toUniversalTime(dateTime)
511
457
 
512
- for newFormat in string.gmatch(format, matchString) do
513
- formatsRequired[#formatsRequired + 1] = newFormat
458
+ if normalized == "millisecond" then
459
+ return dateTime
460
+ elseif normalized == "second" then
461
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second)
462
+ elseif normalized == "minute" then
463
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, t.Hour, t.Minute)
464
+ elseif normalized == "hour" then
465
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, t.Hour)
466
+ elseif normalized == "day" then
467
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day)
468
+ elseif normalized == "week" then
469
+ return Time.subtract(DateTime.fromUniversalTime(t.Year, t.Month, t.Day), Time.getDayOfTheWeek(dateTime), "day")
470
+ elseif normalized == "month" then
471
+ return DateTime.fromUniversalTime(t.Year, t.Month)
472
+ elseif normalized == "quarter" then
473
+ return DateTime.fromUniversalTime(t.Year, (t.Month - 1) // 3 * 3 + 1)
474
+ elseif normalized == "year" then
475
+ return DateTime.fromUniversalTime(t.Year)
476
+ else
477
+ error(string.format("Bad unit %q", normalized))
514
478
  end
479
+ end
515
480
 
516
- for _, formatType in formatsRequired do
517
- returnString = string.gsub(returnString, formatType, string.rep(formatType, 3))
481
+ --[=[
482
+ Returns a `DateTime` at the last millisecond of the unit containing `currentTime`:
483
+ `endOf(t, "day")` is 23:59:59.999. See [Time.startOf].
484
+ ]=]
485
+ function Time.endOf(currentTime: DateTimeLike, unit: TimeUnit): DateTime
486
+ local nextStart = Time.add(Time.startOf(currentTime, unit), 1, unit)
487
+ return DateTime.fromUnixTimestampMillis(nextStart.UnixTimestampMillis - 1)
488
+ end
489
+
490
+ --[=[
491
+ A field of a time for [Time.get] and [Time.set], singular or plural, or one of the
492
+ shorthands `y`, `M`, `D`, `d`, `h`, `m`, `s` and `ms`. `date` is the day of the month and
493
+ `day` is the day of the week (0 is Sunday). `month` runs 1-12.
494
+
495
+ @type TimeField "year" | "month" | "date" | "day" | "hour" | "minute" | "second" | "millisecond" | plurals | shorthands
496
+ @within Time
497
+ ]=]
498
+ export type TimeField =
499
+ "year"
500
+ | "years"
501
+ | "y"
502
+ | "month"
503
+ | "months"
504
+ | "M"
505
+ | "date"
506
+ | "dates"
507
+ | "D"
508
+ | "day"
509
+ | "days"
510
+ | "d"
511
+ | "hour"
512
+ | "hours"
513
+ | "h"
514
+ | "minute"
515
+ | "minutes"
516
+ | "m"
517
+ | "second"
518
+ | "seconds"
519
+ | "s"
520
+ | "millisecond"
521
+ | "milliseconds"
522
+ | "ms"
523
+
524
+ type CanonicalTimeField = "year" | "month" | "date" | "day" | "hour" | "minute" | "second" | "millisecond"
525
+
526
+ local TIME_FIELD_ALIASES: { [string]: CanonicalTimeField } = {
527
+ year = "year",
528
+ years = "year",
529
+ y = "year",
530
+ month = "month",
531
+ months = "month",
532
+ M = "month",
533
+ date = "date",
534
+ dates = "date",
535
+ D = "date",
536
+ day = "day",
537
+ days = "day",
538
+ d = "day",
539
+ hour = "hour",
540
+ hours = "hour",
541
+ h = "hour",
542
+ minute = "minute",
543
+ minutes = "minute",
544
+ m = "minute",
545
+ second = "second",
546
+ seconds = "second",
547
+ s = "second",
548
+ millisecond = "millisecond",
549
+ milliseconds = "millisecond",
550
+ ms = "millisecond",
551
+ }
552
+
553
+ function Time._normalizeField(field: TimeField): CanonicalTimeField
554
+ local normalized = TIME_FIELD_ALIASES[field]
555
+ assert(normalized, string.format("Bad field %q", tostring(field)))
556
+ return normalized :: CanonicalTimeField
557
+ end
558
+
559
+ -- Like JavaScript's Date setters: a month or day past the end of its range rolls into the next
560
+ -- period, and 0 or a negative day rolls back into the previous one.
561
+ function Time._fromUniversalTimeOverflowing(
562
+ year: number,
563
+ month: number,
564
+ day: number,
565
+ hour: number,
566
+ minute: number,
567
+ second: number,
568
+ millisecond: number
569
+ ): DateTime
570
+ local monthIndex = month - 1
571
+ local firstOfMonth =
572
+ DateTime.fromUniversalTime(year + monthIndex // 12, monthIndex % 12 + 1, 1, hour, minute, second, millisecond)
573
+
574
+ return Time.add(firstOfMonth, day - 1, "day")
575
+ end
576
+
577
+ --[=[
578
+ Reads one field of the given time.
579
+
580
+ ```lua
581
+ Time.get("2025-09-22T13:45:30Z", "date") --> 22
582
+ Time.get("2025-09-22T13:45:30Z", "day") --> 1 (Monday)
583
+ ```
584
+ ]=]
585
+ function Time.get(currentTime: DateTimeLike, field: TimeField): number
586
+ local normalized = Time._normalizeField(field)
587
+
588
+ if normalized == "day" then
589
+ return Time.getDayOfTheWeek(currentTime)
518
590
  end
519
591
 
520
- for _, formatType in formatsRequired do
521
- local replacement = ISO_FORMAT_STRINGS[formatType](resolvedTime)
522
- returnString = string.gsub(returnString, string.rep(formatType, 3), tostring(replacement))
592
+ local t = Time._toUniversalTime(currentTime)
593
+
594
+ if normalized == "year" then
595
+ return t.Year
596
+ elseif normalized == "month" then
597
+ return t.Month
598
+ elseif normalized == "date" then
599
+ return t.Day
600
+ elseif normalized == "hour" then
601
+ return t.Hour
602
+ elseif normalized == "minute" then
603
+ return t.Minute
604
+ elseif normalized == "second" then
605
+ return t.Second
606
+ elseif normalized == "millisecond" then
607
+ return t.Millisecond
608
+ else
609
+ error(string.format("Bad field %q", normalized))
610
+ end
611
+ end
612
+
613
+ --[=[
614
+ Returns a `DateTime` with one field replaced. Values outside the field's
615
+ range roll over the way JavaScript dates do: month 13 is January of the next year, date 0 is
616
+ the last day of the previous month, hour 25 is 1am the next day. Setting `day` moves within
617
+ the current week, so 0 is the preceding Sunday.
618
+
619
+ ```lua
620
+ Time.set("2025-09-22T13:45:30Z", "date", 1) --> 2025-09-01T13:45:30Z
621
+ Time.set("2025-09-22T13:45:30Z", "day", 0) --> 2025-09-21T13:45:30Z
622
+ ```
623
+ ]=]
624
+ function Time.set(currentTime: DateTimeLike, field: TimeField, value: number): DateTime
625
+ assert(type(value) == "number", "Bad value")
626
+
627
+ local dateTime = Time._toDateTime(currentTime)
628
+ local normalized = Time._normalizeField(field)
629
+ local t = Time._toUniversalTime(dateTime)
630
+ local whole = math.floor(value)
631
+
632
+ if normalized == "year" then
633
+ return Time._fromUniversalTimeOverflowing(whole, t.Month, t.Day, t.Hour, t.Minute, t.Second, t.Millisecond)
634
+ elseif normalized == "month" then
635
+ return Time._fromUniversalTimeOverflowing(t.Year, whole, t.Day, t.Hour, t.Minute, t.Second, t.Millisecond)
636
+ elseif normalized == "date" then
637
+ return Time._fromUniversalTimeOverflowing(t.Year, t.Month, whole, t.Hour, t.Minute, t.Second, t.Millisecond)
638
+ elseif normalized == "day" then
639
+ return Time.add(dateTime, whole - Time.getDayOfTheWeek(dateTime), "day")
640
+ elseif normalized == "hour" then
641
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, whole, t.Minute, t.Second, t.Millisecond)
642
+ elseif normalized == "minute" then
643
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, t.Hour, whole, t.Second, t.Millisecond)
644
+ elseif normalized == "second" then
645
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, whole, t.Millisecond)
646
+ elseif normalized == "millisecond" then
647
+ return DateTime.fromUniversalTime(t.Year, t.Month, t.Day, t.Hour, t.Minute, t.Second, whole)
648
+ else
649
+ error(string.format("Bad field %q", normalized))
523
650
  end
651
+ end
652
+
653
+ -- Tokens FormatUniversalTime does not offer. Documented on Time.format.
654
+ local EXTENDED_FORMAT_TOKENS: { [string]: (DateTime, string) -> string } = {
655
+ Do = function(dateTime: DateTime, locale: string): string
656
+ return NumberLocalizationOrdinalUtils.localize(Time.getDayOfTheMonth(dateTime), locale)
657
+ end,
658
+ DDDo = function(dateTime: DateTime, locale: string): string
659
+ return NumberLocalizationOrdinalUtils.localize(Time.getDay(dateTime), locale)
660
+ end,
661
+ t = function(dateTime: DateTime): string
662
+ return tostring(Time.getDaysInMonth(dateTime))
663
+ end,
664
+ LY = function(dateTime: DateTime): string
665
+ return tostring(Time.isLeapYear(dateTime))
666
+ end,
667
+ X = function(dateTime: DateTime): string
668
+ return tostring(Time.getUnixTimestamp(dateTime))
669
+ end,
670
+ J = function(dateTime: DateTime): string
671
+ return tostring(Time.getJulianDate(dateTime))
672
+ end,
673
+ }
674
+
675
+ -- Longest first so "DDDo" wins over "Do"
676
+ local EXTENDED_FORMAT_TOKENS_BY_LENGTH: { string } = {}
677
+ do
678
+ for token, _ in EXTENDED_FORMAT_TOKENS do
679
+ table.insert(EXTENDED_FORMAT_TOKENS_BY_LENGTH, token)
680
+ end
681
+ table.sort(EXTENDED_FORMAT_TOKENS_BY_LENGTH, function(a, b)
682
+ return #a > #b
683
+ end)
684
+ end
685
+
686
+ function Time._matchExtendedToken(format: string, index: number): string?
687
+ for _, token in EXTENDED_FORMAT_TOKENS_BY_LENGTH do
688
+ if string.sub(format, index, index + #token - 1) == token then
689
+ return token
690
+ end
691
+ end
692
+
693
+ return nil
694
+ end
695
+
696
+ --[=[
697
+ Formats the given time. The format string is passed to
698
+ [DateTime:FormatUniversalTime](https://create.roblox.com/docs/reference/engine/datatypes/DateTime#FormatUniversalTime)
699
+ with the given locale, so every Roblox token works, for example `"YYYY-MM-DD HH:mm:ss"`
700
+ or `"dddd, MMMM D"`. On top of those, these tokens are available, for example
701
+ `"MMMM Do, YYYY"` gives `September 22nd, 2025`. Their spellings avoid Roblox's own letters,
702
+ so `S` (fractional seconds) and `L` (locale composites) keep their Roblox meaning.
703
+
704
+ | Token | Output |
705
+ | ----- | ------ |
706
+ | `Do` | Day of the month as a localized ordinal, e.g. `22nd` or `22e` |
707
+ | `DDDo` | Day of the year as a localized ordinal, e.g. `265th` |
708
+ | `t` | Days in the month, e.g. `30` |
709
+ | `LY` | Leap year, `true` or `false` |
710
+ | `X` | Unix timestamp in seconds |
711
+ | `J` | Julian day number |
712
+
713
+ Wrap literal text in square brackets to keep it from being read as tokens:
714
+ `"[Today is] dddd"` gives `Today is Monday`.
715
+
716
+ Defaults to the current time and the `en-us` locale.
717
+ ]=]
718
+ function Time.format(format: string, currentTime: DateTimeLike, locale: string?): string
719
+ local dateTime = Time._toDateTime(currentTime)
720
+ local resolvedLocale = locale or DEFAULT_LOCALE
721
+
722
+ local parts: { string } = {}
723
+ local pending = ""
724
+
725
+ local index = 1
726
+ while index <= #format do
727
+ local char = string.sub(format, index, index)
728
+ local token = Time._matchExtendedToken(format, index)
729
+
730
+ if char == "[" then
731
+ -- Bracketed text is literal for FormatUniversalTime too, so hand it over whole
732
+ local closeIndex = string.find(format, "]", index, true) or #format
733
+ pending ..= string.sub(format, index, closeIndex)
734
+ index = closeIndex + 1
735
+ elseif token then
736
+ if pending ~= "" then
737
+ table.insert(parts, dateTime:FormatUniversalTime(pending, resolvedLocale))
738
+ pending = ""
739
+ end
740
+ table.insert(parts, EXTENDED_FORMAT_TOKENS[token](dateTime, resolvedLocale))
741
+ index += #token
742
+ else
743
+ pending ..= char
744
+ index += 1
745
+ end
746
+ end
747
+
748
+ if pending ~= "" then
749
+ table.insert(parts, dateTime:FormatUniversalTime(pending, resolvedLocale))
750
+ end
751
+
752
+ return table.concat(parts)
753
+ end
754
+
755
+ --[=[
756
+ Returns a `DateTime` with the second replaced. See [Time.set].
757
+ ]=]
758
+ function Time.setSecond(currentTime: DateTimeLike, second: number): DateTime
759
+ return Time.set(currentTime, "second", second)
760
+ end
761
+
762
+ --[=[
763
+ Returns a `DateTime` with the minute replaced. See [Time.set].
764
+ ]=]
765
+ function Time.setMinute(currentTime: DateTimeLike, minute: number): DateTime
766
+ return Time.set(currentTime, "minute", minute)
767
+ end
768
+
769
+ --[=[
770
+ Returns a `DateTime` with the 24-hour hour replaced. See [Time.set].
771
+ ]=]
772
+ function Time.setHour(currentTime: DateTimeLike, hour: number): DateTime
773
+ return Time.set(currentTime, "hour", hour)
774
+ end
775
+
776
+ --[=[
777
+ Returns a `DateTime` with the 12-hour hour replaced, staying in the same half of the day, so
778
+ setting 3 on a 13:45 time gives 15:45. 12 is midnight in the morning and noon in the afternoon.
779
+ ]=]
780
+ function Time.setRegularHour(currentTime: DateTimeLike, hour: number): DateTime
781
+ assert(type(hour) == "number", "Bad hour")
782
+
783
+ local isAfternoon = Time.getHour(currentTime) >= 12
784
+ return Time.set(currentTime, "hour", hour % 12 + (if isAfternoon then 12 else 0))
785
+ end
786
+
787
+ --[=[
788
+ Returns a `DateTime` with the day of the year (1-366) replaced, keeping the clock. A day past
789
+ the end of the year rolls into the next one.
790
+ ]=]
791
+ function Time.setDay(currentTime: DateTimeLike, day: number): DateTime
792
+ assert(type(day) == "number", "Bad day")
793
+
794
+ local t = Time._toUniversalTime(currentTime)
795
+ return Time._fromUniversalTimeOverflowing(t.Year, 1, math.floor(day), t.Hour, t.Minute, t.Second, t.Millisecond)
796
+ end
797
+
798
+ --[=[
799
+ Returns a `DateTime` with the year replaced. See [Time.set].
800
+ ]=]
801
+ function Time.setYear(currentTime: DateTimeLike, year: number): DateTime
802
+ return Time.set(currentTime, "year", year)
803
+ end
804
+
805
+ --[=[
806
+ Returns a `DateTime` with the month (1-12) replaced. See [Time.set].
807
+ ]=]
808
+ function Time.setMonth(currentTime: DateTimeLike, month: number): DateTime
809
+ return Time.set(currentTime, "month", month)
810
+ end
811
+
812
+ --[=[
813
+ Returns a `DateTime` with the day of the month replaced. See [Time.set].
814
+ ]=]
815
+ function Time.setDayOfTheMonth(currentTime: DateTimeLike, dayOfTheMonth: number): DateTime
816
+ return Time.set(currentTime, "date", dayOfTheMonth)
817
+ end
818
+
819
+ --[=[
820
+ Returns a `DateTime` with the day of the week (0-6, starting on Sunday) replaced, moving
821
+ within the current week. See [Time.set].
822
+ ]=]
823
+ function Time.setDayOfTheWeek(currentTime: DateTimeLike, dayOfTheWeek: number): DateTime
824
+ return Time.set(currentTime, "day", dayOfTheWeek)
825
+ end
826
+
827
+ --[=[
828
+ Returns a `DateTime` on the given Julian day number, keeping the clock.
829
+ ]=]
830
+ function Time.setJulianDate(currentTime: DateTimeLike, julianDate: number): DateTime
831
+ assert(type(julianDate) == "number", "Bad julianDate")
832
+
833
+ local dateTime = Time._toDateTime(currentTime)
834
+ local millisecondsIntoDay = dateTime.UnixTimestampMillis % (SECONDS_PER_DAY * 1000)
835
+ local unixDay = math.floor(julianDate) - UNIX_EPOCH_JULIAN_DAY
524
836
 
525
- return returnString
837
+ return DateTime.fromUnixTimestampMillis(unixDay * SECONDS_PER_DAY * 1000 + millisecondsIntoDay)
526
838
  end
527
839
 
528
840
  return Time