UNPKG

date-time-format-icu

Version:

This package provides a simple and flexible way to format JavaScript dates

67 lines (65 loc) 2.54 kB
// src/types.ts var DateFormat = /* @__PURE__ */ ((DateFormat2) => { DateFormat2["short"] = "M/d/yy, h:mm a"; DateFormat2["medium"] = "MMM d, y, h:mm:ss a"; DateFormat2["long"] = "MMMM d, y, h:mm:ss a z"; DateFormat2["full"] = "EEEE, MMMM d, y, h:mm:ss a zzzz"; DateFormat2["shortDate"] = "M/d/yy"; DateFormat2["mediumDate"] = "MMM d, y"; DateFormat2["longDate"] = "MMMM d, y"; DateFormat2["fullDate"] = "EEEE, MMMM d, y"; DateFormat2["shortTime"] = "h:mm a"; DateFormat2["mediumTime"] = "h:mm:ss a"; DateFormat2["longTime"] = "h:mm:ss a z"; DateFormat2["fullTime"] = "h:mm:ss a zzzz"; return DateFormat2; })(DateFormat || {}); // src/index.ts function dateFormatter(input, format = "medium", locale = "en-US") { let date; if (input instanceof Date) { date = input; } else if (typeof input === "string" || typeof input === "number") { const parsed = new Date(input); if (isNaN(parsed.getTime())) { return "Invalid Date"; } date = parsed; } else { return "Invalid Input"; } const formatString = DateFormat[format] || format; try { return new Intl.DateTimeFormat(locale, buildIntlOptions(formatString)).format(date); } catch (err) { return date.toISOString(); } } function buildIntlOptions(format) { const options = {}; if (format.indexOf("y") !== -1) options.year = "numeric"; if (format.indexOf("yy") !== -1 && format.indexOf("yyy") === -1) options.year = "2-digit"; if (format.indexOf("MMMM") !== -1) options.month = "long"; else if (format.indexOf("MMM") !== -1) options.month = "short"; else if (format.indexOf("MM") !== -1) options.month = "2-digit"; else if (format.indexOf("M") !== -1) options.month = "numeric"; if (format.indexOf("dd") !== -1) options.day = "2-digit"; else if (format.indexOf("d") !== -1) options.day = "numeric"; if (format.indexOf("EEEE") !== -1) options.weekday = "long"; else if (format.indexOf("EEE") !== -1) options.weekday = "short"; if (format.indexOf("hh") !== -1 || format.indexOf("h") !== -1) { options.hour = "2-digit"; options.hour12 = true; } else if (format.indexOf("HH") !== -1 || format.indexOf("H") !== -1) { options.hour = "2-digit"; options.hour12 = false; } if (format.indexOf("mm") !== -1) options.minute = "2-digit"; if (format.indexOf("ss") !== -1) options.second = "2-digit"; if (format.indexOf("zzzz") !== -1) options.timeZoneName = "long"; else if (format.indexOf("z") !== -1) options.timeZoneName = "short"; return options; } export { dateFormatter };