UNPKG

@atlaskit/editor-common

Version:

A package that contains common classes and components for editor and renderer

80 lines (78 loc) 2.93 kB
import differenceInCalendarDays from 'date-fns/differenceInCalendarDays'; import isBefore from 'date-fns/isBefore'; var FORMATS = /*#__PURE__*/function (FORMATS) { FORMATS["ISO_FORMAT"] = "YYYY-MM-DD"; FORMATS["LOCALIZED_FORMAT"] = "LOCALIZED_FORMAT"; return FORMATS; }(FORMATS || {}); export const timestampToUTCDate = timestamp => { const date = new Date(Number(timestamp)); const day = date.getUTCDate(); const month = date.getUTCMonth() + 1; const year = date.getUTCFullYear(); return { day, month, year }; }; export const todayTimestampInUTC = timeZone => { const today = new Date(Date.now()); if (timeZone) { var _parts$find, _parts$find2, _parts$find3; const parts = new Intl.DateTimeFormat('en-US', { timeZone, year: 'numeric', month: 'numeric', day: 'numeric' }).formatToParts(today); const year = Number((_parts$find = parts.find(p => p.type === 'year')) === null || _parts$find === void 0 ? void 0 : _parts$find.value); const month = Number((_parts$find2 = parts.find(p => p.type === 'month')) === null || _parts$find2 === void 0 ? void 0 : _parts$find2.value) - 1; const day = Number((_parts$find3 = parts.find(p => p.type === 'day')) === null || _parts$find3 === void 0 ? void 0 : _parts$find3.value); return Date.UTC(year, month, day).toString(); } const todayInUTC = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate()); return todayInUTC.toString(); }; const addLeadingZero = val => { if (val < 10) { return `0${val}`; } return val; }; const capitalizeFirstLetter = str => { return str.charAt(0).toUpperCase() + str.slice(1); }; // example: "23 Jan 2018" export const timestampToString = (timestamp, intl, pattern) => { if (!intl || pattern === FORMATS.ISO_FORMAT) { return timestampToIsoFormat(timestamp); } const date = new Date(Number(timestamp)); return intl.formatDate(date, { timeZone: 'UTC', month: 'short', day: 'numeric', year: 'numeric', formatMatcher: 'best fit' }); }; // example: "2018-01-23" export const timestampToIsoFormat = timestamp => { const date = new Date(Number(timestamp)); return `${date.getUTCFullYear()}-${addLeadingZero(date.getUTCMonth() + 1)}-${addLeadingZero(date.getUTCDate())}`; }; export const isPastDate = (timestamp, timeZone) => { return isBefore(new Date(Number(timestamp)), new Date(Number(todayTimestampInUTC(timeZone)))); }; export const timestampToTaskContext = (timestamp, intl, timeZone) => { const curDate = new Date(Number(todayTimestampInUTC(timeZone))); const givenDate = new Date(Number(timestamp)); const distance = differenceInCalendarDays(givenDate, curDate); if (intl && [-1, 0, 1].indexOf(distance) > -1) { return capitalizeFirstLetter(intl.formatRelativeTime(distance, 'day', { numeric: 'auto' })); } return timestampToString(timestamp, intl, FORMATS.LOCALIZED_FORMAT); };