UNPKG

ritm-date

Version:

Date & time lightweight formatter

59 lines (58 loc) 2.47 kB
import { locales } from './locales'; const pad = (n, len = 2) => String(n).padStart(len, '0'); const getOffsetString = (date) => { const offsetMinutes = -date.getTimezoneOffset(); const sign = offsetMinutes >= 0 ? '+' : '-'; const absMinutes = Math.abs(offsetMinutes); const hours = pad(Math.floor(absMinutes / 60)); const minutes = pad(absMinutes % 60); return `${sign}${hours}:${minutes}`; }; const applyMask = (mask, parts) => { const tokens = Object.keys(parts).sort((a, b) => b.length - a.length); const abbreviationsRegex = new RegExp(tokens.join('|'), 'g'); return mask.replace(abbreviationsRegex, match => { var _a; return (_a = parts[match]) !== null && _a !== void 0 ? _a : match; }); }; export const formatDate = (date, mask, locale = 'en', originalInput) => { const loc = locales[locale || 'en']; let targetDate = date; if (!mask.includes('ZZ') && typeof originalInput === 'string') { const match = originalInput.match(/([+-]\d{2}):?(\d{2})$|Z$/); if (match) { if (!(match[0] === 'Z' || match[0] === '+00' || match[0] === '+00:00' || match[0] === '-00:00')) { // Has not nullish diff const [, hh, mm] = match; const offsetMinutes = parseInt(hh, 10) * 60 + parseInt(mm, 10); const localOffset = -date.getTimezoneOffset(); const diff = (offsetMinutes - localOffset) * 60 * 1000; targetDate = new Date(date.getTime() + diff); } } else { const diff = -date.getTimezoneOffset() * 60 * 1000; targetDate = new Date(date.getTime() + diff); } } const monthIndex = targetDate.getMonth(); const day = targetDate.getDay(); const parts = { YYYY: String(targetDate.getFullYear()), YY: String(targetDate.getFullYear()).slice(-2), MM: pad(monthIndex + 1), DD: pad(targetDate.getDate()), D: String(targetDate.getDate()), ddd: loc.weekDays[day - 1], dd: loc.shortWeekDays[day - 1], HH: pad(targetDate.getHours()), h: String(targetDate.getHours()), mm: pad(targetDate.getMinutes()), ss: pad(targetDate.getSeconds()), MMMM: loc.months[monthIndex] || '', MMM: loc.shortMonths[monthIndex] || '', ZZ: getOffsetString(targetDate) }; return applyMask(mask, parts); };