UNPKG

@chayns-components/date

Version:

A set of beautiful React components for developing your own applications with chayns.

63 lines (62 loc) 2.16 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useDateInfo = void 0; var _chaynsApi = require("chayns-api"); var _react = require("react"); var _dateInfo = require("../utils/dateInfo"); const useDateInfo = ({ date, shouldShowDateToNowDifference, shouldShowRelativeDayOfWeek, shouldShowDayOfWeek, shouldShowTime, shouldUseShortText, shouldShowYear, preText }) => { const { active: language } = (0, _chaynsApi.getLanguage)(); const [formattedDate, setFormattedDate] = (0, _react.useState)(date.toLocaleDateString()); const [currentDate, setCurrentDate] = (0, _react.useState)(new Date()); (0, _react.useEffect)(() => { if (shouldShowDateToNowDifference) { return; } setFormattedDate((0, _dateInfo.getDateInfo)({ date, shouldShowYear, shouldShowTime, shouldUseShortText, shouldShowDayOfWeek, shouldShowRelativeDayOfWeek })); }, [date, shouldShowDateToNowDifference, shouldShowDayOfWeek, shouldShowRelativeDayOfWeek, shouldShowTime, shouldShowYear, shouldUseShortText]); (0, _react.useEffect)(() => { if (!shouldShowDateToNowDifference) return () => {}; const updateCurrentDate = () => setCurrentDate(new Date()); const now = new Date(); const timeDiffInMs = Math.abs(date.getTime() - now.getTime()); const updateInterval = timeDiffInMs < 60000 ? 1000 : 60000 - now.getSeconds() * 1000; const intervalId = setInterval(updateCurrentDate, 1000); const timeout = setTimeout(updateCurrentDate, updateInterval); return () => { clearTimeout(timeout); clearInterval(intervalId); }; }, [date, shouldShowDateToNowDifference]); (0, _react.useEffect)(() => { if (shouldShowDateToNowDifference) { setFormattedDate((0, _dateInfo.getTimeTillNow)({ date, currentDate, language })); } }, [date, currentDate, language, shouldShowDateToNowDifference]); return (0, _react.useMemo)(() => `${preText ? `${preText.trim()} ` : ''}${formattedDate}`, [formattedDate, preText]); }; exports.useDateInfo = useDateInfo; //# sourceMappingURL=useDateInfo.js.map