UNPKG

@kubit-ui-web/react-components

Version:

Kubit React Components is a customizable, accessible library of React web components, designed to enhance your application's user experience

63 lines 3.06 kB
import { FORMATTING_TOKENS } from './constants/common.constant'; import { MACRO_TOKEN_TO_FORMAT_OPTS } from './constants/format.constant'; import { locale } from './locale'; import { isValidDate } from './validateDate'; const addZero = (value) => `${value < 10 ? '0' : ''}${value}`; export const formatDate = (date, format) => { const formatAux = typeof format === 'string' ? MACRO_TOKEN_TO_FORMAT_OPTS[format] : format; if (typeof format === 'string' && !formatAux) { const formatParts = format.match(FORMATTING_TOKENS) || []; const matches = { YY: ['year', (value) => `${new Date(value).getFullYear()}`.slice(-2)], YYYY: ['year', (value) => `${new Date(value).getFullYear()}`], M: ['month', (value) => `${new Date(value).getMonth() + 1}`], MM: ['month', (value) => `${addZero(new Date(value).getMonth() + 1)}`], MMM: [ 'month', (value) => new Date(value).toLocaleString(locale.getLocale(), { month: 'short' }), ], MMMM: [ 'month', (value) => new Date(value).toLocaleString(locale.getLocale(), { month: 'long' }), ], D: ['day', (value) => `${new Date(value).getDate()}`], DD: ['day', (value) => `${addZero(new Date(value).getDate())}`], W: [ 'weekday', (value) => new Date(value).toLocaleString(locale.getLocale(), { weekday: 'short' }), ], WW: [ 'weekday', (value) => new Date(value).toLocaleString(locale.getLocale(), { weekday: 'long' }), ], H: ['hour', (value) => `${new Date(value).getHours()}`], HH: ['hour', (value) => `${addZero(new Date(value).getHours())}`], m: ['minute', (value) => `${new Date(value).getMinutes()}`], mm: ['minute', (value) => `${addZero(new Date(value).getMinutes())}`], s: ['second', (value) => `${new Date(value).getSeconds()}`], ss: ['second', (value) => `${addZero(new Date(value).getSeconds())}`], }; const values = formatParts.map((token) => { const parseTo = matches[token]; const key = parseTo && parseTo[0]; const value = parseTo && parseTo[1](date); return key ? value : token; }); return values.join('').replace(/[\\[\]]/g, ''); } return date.toLocaleString(locale.getLocale(), { ...formatAux, }); }; export const formatDateToUTC = (date) => { const dateObj = new Date(date); if (!isValidDate(dateObj)) { throw Error('Date is invalid'); } // If the date object has a time of 00:00:00, return the date object because it is already in UTC if (dateObj.getHours() === 0 && dateObj.getMinutes() === 0 && dateObj.getSeconds() === 0) { return dateObj; } return new Date(new Intl.DateTimeFormat('en-US', { timeZone: 'UTC' }).format(new Date(date))); }; //# sourceMappingURL=formatDate.js.map