formatDate fixed
This commit is contained in:
@ -3,8 +3,9 @@
|
|||||||
<script type="module">
|
<script type="module">
|
||||||
import {formatDate} from './dist/index.mjs';
|
import {formatDate} from './dist/index.mjs';
|
||||||
|
|
||||||
console.log(formatDate('YYYY-MM-DD HH:mm A z'));
|
const dt = new Date('2021-03-03T09:00:00Z');
|
||||||
console.log(formatDate('YYYY-MM-DD HH:mm A Z'));
|
const result = formatDate('Do MMMM dddd', dt, 0);
|
||||||
|
console.log(result);
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
20
src/math.ts
20
src/math.ts
@ -49,12 +49,16 @@ export function fracToDec(frac: string) {
|
|||||||
return whole + (Number(split[0]) / Number(split[1]));
|
return whole + (Number(split[0]) / Number(split[1]));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function numSuffix(num: number): string {
|
/**
|
||||||
if (num % 100 >= 11 && num % 100 <= 13) return `${num}th`;
|
* Add a suffix to a number:
|
||||||
switch (num % 10) {
|
* 1 = 1st
|
||||||
case 1: return `${num}st`;
|
* 2 = 2nd
|
||||||
case 2: return `${num}nd`;
|
* 3 = 3rd
|
||||||
case 3: return `${num}rd`;
|
* N = Nth
|
||||||
default: return `${num}th`;
|
* @param {number} n
|
||||||
}
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function numSuffix(n: number): string {
|
||||||
|
const s = ['th', 'st', 'nd', 'rd'], v = n % 100;
|
||||||
|
return `${n}${s[(v - 20) % 10] || s[v] || s[0]}`;
|
||||||
}
|
}
|
||||||
|
137
src/time.ts
137
src/time.ts
@ -1,3 +1,5 @@
|
|||||||
|
import {numSuffix} from './math.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Like setInterval but will adjust the timeout value to account for runtime
|
* Like setInterval but will adjust the timeout value to account for runtime
|
||||||
* @param {Function} cb Callback function that will be ran
|
* @param {Function} cb Callback function that will be ran
|
||||||
@ -20,13 +22,12 @@ export function adjustedInterval(cb: Function, ms: number) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function dayOfWeek(d: number): string {
|
||||||
export function dayOfWeek(num: number): string {
|
return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d];
|
||||||
return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][num] || 'Unknown';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dayOfYear(date: Date): number {
|
export function dayOfYear(date: Date): number {
|
||||||
const start = new Date(`${date.getFullYear()}-01-01T00:00:00Z`);
|
const start = new Date(Date.UTC(date.getUTCFullYear(), 0, 1));
|
||||||
return Math.ceil((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
|
return Math.ceil((date.getTime() - start.getTime()) / (1000 * 60 * 60 * 24));
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,86 +44,90 @@ export function formatDate(format: string = 'YYYY-MM-DD H:mm', date: Date | numb
|
|||||||
if (isNaN(date.getTime())) throw new Error('Invalid date input');
|
if (isNaN(date.getTime())) throw new Error('Invalid date input');
|
||||||
const numericTz = typeof tz === 'number';
|
const numericTz = typeof tz === 'number';
|
||||||
const localTz = tz === 'local' || (!numericTz && tz.toLowerCase?.() === 'local');
|
const localTz = tz === 'local' || (!numericTz && tz.toLowerCase?.() === 'local');
|
||||||
const offsetMinutes = numericTz ? tz * 60 : 0;
|
const tzName = localTz ? Intl.DateTimeFormat().resolvedOptions().timeZone : numericTz ? 'UTC' : tz;
|
||||||
const adjustedDate = date;
|
|
||||||
const tzName = localTz ? Intl.DateTimeFormat().resolvedOptions().timeZone : numericTz ? `UTC${tz >= 0 ? '+' : ''}${tz}` : tz;
|
if (!numericTz && tzName !== 'UTC') {
|
||||||
|
try {
|
||||||
|
new Intl.DateTimeFormat('en-US', { timeZone: tzName }).format();
|
||||||
|
} catch {
|
||||||
|
throw new Error(`Invalid timezone: ${tzName}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let zonedDate = new Date(date);
|
||||||
|
if (!numericTz && tzName !== 'UTC') {
|
||||||
|
const parts = new Intl.DateTimeFormat('en-US', {
|
||||||
|
timeZone: tzName,
|
||||||
|
year: 'numeric', month: '2-digit', day: '2-digit',
|
||||||
|
hour: '2-digit', minute: '2-digit', second: '2-digit',
|
||||||
|
hour12: false
|
||||||
|
}).formatToParts(date);
|
||||||
|
const get = (type: string) => parts.find(p => p.type === type)?.value;
|
||||||
|
const build = `${get('year')}-${get('month')}-${get('day')}T${get('hour')}:${get('minute')}:${get('second')}Z`;
|
||||||
|
zonedDate = new Date(build);
|
||||||
|
} else if (numericTz || tzName === 'UTC') {
|
||||||
|
const offset = numericTz ? tz as number : 0;
|
||||||
|
zonedDate = new Date(date.getTime() + offset * 60 * 60 * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
const get = (fn: 'FullYear' | 'Month' | 'Date' | 'Day' | 'Hours' | 'Minutes' | 'Seconds' | 'Milliseconds') =>
|
||||||
|
(numericTz || tzName === 'UTC') ? zonedDate[`getUTC${fn}`]() : zonedDate[`get${fn}`]();
|
||||||
|
|
||||||
function getTZOffset(): string {
|
function getTZOffset(): string {
|
||||||
if (numericTz) {
|
if (numericTz) {
|
||||||
const hours = Math.floor(Math.abs(offsetMinutes) / 60);
|
const total = (tz as number) * 60;
|
||||||
const minutes = Math.abs(offsetMinutes) % 60;
|
const hours = Math.floor(Math.abs(total) / 60);
|
||||||
return `${offsetMinutes >= 0 ? '+' : '-'}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
|
const mins = Math.abs(total) % 60;
|
||||||
|
return `${tz >= 0 ? '+' : '-'}${String(hours).padStart(2, '0')}:${String(mins).padStart(2, '0')}`;
|
||||||
}
|
}
|
||||||
if (tzName === 'UTC') return '+00:00';
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const parts = new Intl.DateTimeFormat('en-US', {timeZone: tzName, timeZoneName: 'longOffset', hour: '2-digit', minute: '2-digit',}).formatToParts(adjustedDate);
|
const offset = new Intl.DateTimeFormat('en-US', {timeZone: tzName, timeZoneName: 'longOffset', hour: '2-digit', minute: '2-digit',})
|
||||||
const tzPart = parts.find(p => p.type === 'timeZoneName')?.value || '';
|
.formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value.match(/([+-]\d{2}:\d{2})/)?.[1];
|
||||||
const match = tzPart.match(/([+-]\d{2}:\d{2})/);
|
if (offset) return offset;
|
||||||
if (match) return match[1];
|
|
||||||
} catch {}
|
} catch {}
|
||||||
|
return '+00:00';
|
||||||
const dtf = new Intl.DateTimeFormat('en-US', {timeZone: tzName, hour12: false, hour: '2-digit', minute: '2-digit'});
|
|
||||||
const parts = dtf.formatToParts(adjustedDate);
|
|
||||||
const targetHour = Number(parts.find(p => p.type === 'hour')?.value);
|
|
||||||
const targetMinute = Number(parts.find(p => p.type === 'minute')?.value);
|
|
||||||
const utcHour = adjustedDate.getUTCHours();
|
|
||||||
const utcMinute = adjustedDate.getUTCMinutes();
|
|
||||||
|
|
||||||
let offset = (targetHour - utcHour) * 60 + (targetMinute - utcMinute);
|
|
||||||
if (offset > 720) offset -= 1440;
|
|
||||||
if (offset < -720) offset += 1440;
|
|
||||||
|
|
||||||
const sign = offset >= 0 ? '+' : '-';
|
|
||||||
const absOffset = Math.abs(offset);
|
|
||||||
const hours = Math.floor(absOffset / 60);
|
|
||||||
const minutes = absOffset % 60;
|
|
||||||
return `${sign}${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getTZAbbr(): string {
|
function getTZAbbr(): string {
|
||||||
if(numericTz && tz == 0) return 'UTC';
|
if (numericTz && tz === 0) return 'UTC';
|
||||||
try {
|
try {
|
||||||
return new Intl.DateTimeFormat('en-US', { timeZone: tzName, timeZoneName: 'short' })
|
return new Intl.DateTimeFormat('en-US', { timeZone: tzName, timeZoneName: 'short' })
|
||||||
.formatToParts(adjustedDate).find(p => p.type === 'timeZoneName')?.value || '';
|
.formatToParts(<Date>date).find(p => p.type === 'timeZoneName')?.value || '';
|
||||||
} catch {
|
} catch {
|
||||||
return tzName;
|
return tzName;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const formatter = new Intl.DateTimeFormat('en-us', {
|
|
||||||
timeZone: numericTz ? 'UTC' : tzName,
|
|
||||||
year: format.includes('YY') ? 'numeric' : undefined,
|
|
||||||
month: format.includes('MM') || format.includes('M') ? '2-digit' : undefined,
|
|
||||||
day: format.includes('DD') || format.includes('Do') || format.includes('D') ? '2-digit' : undefined,
|
|
||||||
hour: format.includes('HH') || format.includes('hh') || format.includes('H') || format.includes('h') ? '2-digit' : undefined,
|
|
||||||
minute: format.includes('mm') || format.includes('m') ? '2-digit' : undefined,
|
|
||||||
second: format.includes('ss') || format.includes('s') ? '2-digit' : undefined,
|
|
||||||
hourCycle: format.includes('A') || format.includes('a') ? 'h12' : 'h23',
|
|
||||||
});
|
|
||||||
|
|
||||||
const parts = formatter.formatToParts(adjustedDate);
|
|
||||||
const tokens: Record<string, string> = {
|
const tokens: Record<string, string> = {
|
||||||
YYYY: adjustedDate.getFullYear().toString(),
|
YYYY: get('FullYear').toString(),
|
||||||
YY: adjustedDate.getFullYear().toString().slice(2),
|
YY: get('FullYear').toString().slice(2),
|
||||||
MM: parts.find(part => part.type === 'month')?.value || '',
|
MMMM: month(get('Month')),
|
||||||
M: (parseInt(parts.find(part => part.type === 'month')?.value || '0', 10)).toString(),
|
MMM: month(get('Month')).slice(0, 3),
|
||||||
DD: parts.find(part => part.type === 'day')?.value || '',
|
MM: (get('Month') + 1).toString().padStart(2, '0'),
|
||||||
D: parseInt(parts.find(part => part.type === 'day')?.value || '0', 10).toString(),
|
M: (get('Month') + 1).toString(),
|
||||||
HH: parts.find(part => part.type === 'hour')?.value.padStart(2, '0') || '',
|
DDD: dayOfYear(zonedDate).toString(),
|
||||||
H: parseInt(parts.find(part => part.type === 'hour')?.value || '0', 10).toString(),
|
DD: get('Date').toString().padStart(2, '0'),
|
||||||
hh: (parseInt(parts.find(part => part.type === 'hour')?.value || '0', 10) % 12 || 12).toString().padStart(2, '0'),
|
Do: numSuffix(get('Date')),
|
||||||
h: (parseInt(parts.find(part => part.type === 'hour')?.value || '0', 10) % 12 || 12).toString(),
|
D: get('Date').toString(),
|
||||||
mm: parts.find(part => part.type === 'minute')?.value || '',
|
dddd: dayOfWeek(get('Day')),
|
||||||
m: parseInt(parts.find(part => part.type === 'minute')?.value || '0', 10).toString(),
|
ddd: dayOfWeek(get('Day')).slice(0, 3),
|
||||||
ss: parts.find(part => part.type === 'second')?.value || '',
|
HH: get('Hours').toString().padStart(2, '0'),
|
||||||
s: parseInt(parts.find(part => part.type === 'second')?.value || '0', 10).toString(),
|
H: get('Hours').toString(),
|
||||||
A: parseInt(parts.find(part => part.type === 'hour')?.value || '0', 10) >= 12 ? 'PM' : 'AM',
|
hh: (get('Hours') % 12 || 12).toString().padStart(2, '0'),
|
||||||
a: parseInt(parts.find(part => part.type === 'hour')?.value || '0', 10) >= 12 ? 'pm' : 'am',
|
h: (get('Hours') % 12 || 12).toString(),
|
||||||
|
mm: get('Minutes').toString().padStart(2, '0'),
|
||||||
|
m: get('Minutes').toString(),
|
||||||
|
ss: get('Seconds').toString().padStart(2, '0'),
|
||||||
|
s: get('Seconds').toString(),
|
||||||
|
SSS: get('Milliseconds').toString().padStart(3, '0'),
|
||||||
|
A: get('Hours') >= 12 ? 'PM' : 'AM',
|
||||||
|
a: get('Hours') >= 12 ? 'pm' : 'am',
|
||||||
|
ZZ: getTZOffset().replace(':', ''),
|
||||||
Z: getTZOffset(),
|
Z: getTZOffset(),
|
||||||
z: getTZAbbr(),
|
z: getTZAbbr(),
|
||||||
};
|
};
|
||||||
return format.replace(/YYYY|YY|MM|M|DD|D|HH|H|hh|h|mm|m|ss|s|A|a|Z|z/g, token => tokens[token]);
|
|
||||||
|
return format.replace(/YYYY|YY|MMMM|MMM|MM|M|DDD|DD|Do|D|dddd|ddd|HH|H|hh|h|mm|m|ss|s|SSS|A|a|ZZ|Z|z/g, token => tokens[token]);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -137,8 +142,8 @@ export function instantInterval(fn: () => any, interval: number) {
|
|||||||
return setInterval(fn, interval);
|
return setInterval(fn, interval);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function monthString(num: number): string {
|
export function month(m: number): string {
|
||||||
return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][num] || 'Unknown';
|
return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][m];
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -31,11 +31,11 @@ describe('Time Utilities', () => {
|
|||||||
it('handles formatting for given timestamp', () => {
|
it('handles formatting for given timestamp', () => {
|
||||||
const timestamp = Date.UTC(2023, 1, 1, 18, 5, 5, 123); // Feb 1, 2023 18:05:05.123 UTC
|
const timestamp = Date.UTC(2023, 1, 1, 18, 5, 5, 123); // Feb 1, 2023 18:05:05.123 UTC
|
||||||
const formatted = formatDate('YYYY MM DD HH mm ss SSS A Z', timestamp, 'UTC');
|
const formatted = formatDate('YYYY MM DD HH mm ss SSS A Z', timestamp, 'UTC');
|
||||||
expect(formatted).toMatch(/^2023 02 01 18 05 05 123 PM \+?0:00$/i);
|
expect(formatted).toMatch(/^2023 02 01 18 05 05 123 PM \+00:00/i);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('throws for unknown timezone', () => {
|
it('throws for unknown timezone', () => {
|
||||||
expect(() => formatDate('YYYY', new Date(), '???')).toThrowError(/Unknown timezone/);
|
expect(() => formatDate('YYYY', new Date(), '???')).toThrowError(/Invalid timezone/);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('handles timezone by offset number', () => {
|
it('handles timezone by offset number', () => {
|
||||||
|
Reference in New Issue
Block a user