Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 | 542x 542x 1x 542x 44x 542x 542x 10x 542x 167x 542x 6x 4x 4x 4x 4x 4x 4x 542x 542x 542x 96x 96x 96x 96x 96x 96x 96x 96x 542x 542x 96x 96x 96x 542x 542x 262x 192x 70x 51x 2x 49x 19x 542x 542x 2400x 2374x 2374x 49x 2325x 542x 86x 4x 86x 542x 20086x 2188x 20086x 542x 85x 85x 80x 85x 40x 40x 40x 85x 32x 32x 32x 32x 32x 32x 32x 85x 542x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 542x 542x 542x 2406x 1342x 16x 3x 13x 1326x 1323x 1323x 1323x 3x 542x 8x 8x 8x 8x 8x 8x 8x 542x 2656x 286x 2370x 542x 8x 542x 31x 29x 17x 10x 10x 10x 12x 542x 5x 5x 542x 7x 7x 7x 7x 7x 7x 7x 542x 29546x 29546x 29546x 29546x 29546x 29546x 29546x 9847x 19699x 542x | import { parse } from "date-fns";
import { formatInTimeZone, toDate, zonedTimeToUtc } from "date-fns-tz";
import { PLATFORM_TIMEZONE } from "./timezones";
import moment from "moment-timezone";
import { format } from "date-fns";
export const toUnixTimeWithTime = (date: Date, time: string): number | null => {
if (!date) return null;
if (isNaN(date.getTime())) return null;
if (time && time.trim() !== "") {
const [timeString, meridian] = time.split(" ");
const [hours, minutes] = timeString.split(":").map(Number);
let adjustedHours = hours % 12;
if (meridian.toLowerCase() === "pm") {
adjustedHours += 12;
}
date.setHours(adjustedHours, minutes || 0, 0, 0);
}
return Math.floor(date.getTime() / 1000);
};
export const getCurrentYear = () => {
return new Date().getFullYear();
};
export const toUnixDateFormat = (date: Date) =>
Math.floor(date?.getTime() / 1000);
export const adjustDateToUTC = (date: Date) => {
return new Date(
Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()),
);
};
export const convertPhoneNumber = (phoneNumber: string): string | null => {
return phoneNumber?.replace("+", "")?.replace(/\s/g, "");
};
export const isEmptyPhone = (phone: any) =>
[null, "", "+", "+1", "1"].includes(phone);
export const fromUnixDateFormat = (
unixTimestamp: number,
withDots?: boolean,
): string => {
if (unixTimestamp == null || isNaN(unixTimestamp * 1000)) return "";
const date = new Date(unixTimestamp * 1000);
const month = (date.getUTCMonth() + 1).toString().padStart(2, "0");
const day = date.getUTCDate().toString().padStart(2, "0");
const year = date.getUTCFullYear().toString();
const formatted = `${month}/${day}/${year}`;
return withDots ? formatted.replace(/\//g, ".") : formatted;
};
export const toUTCStartOfDay = (date: Date) => {
const timezoneOffset = Math.abs(date.getTimezoneOffset());
const hoursTime = timezoneOffset / 60;
date.setHours(hoursTime);
return date;
};
function addPlural(relativeTimeString: string) {
const [amount, unit] = relativeTimeString.split(" ");
if (amount === "1") {
return {
amount,
unit: unit + "s",
};
}
return {
amount,
unit,
};
}
export const parseRelativeTimeString = (relativeTimeString: string) => {
if (relativeTimeString === "")
return {
formattedDate: calculateDate(),
};
const { amount, unit } = addPlural(relativeTimeString);
const timeDelta: Record<string, any> = {};
timeDelta[unit] = parseInt(amount);
const formatter = new Intl.DateTimeFormat("it-IT", {
day: "2-digit",
month: "2-digit",
year: "numeric",
});
const now = new Date();
const targetDate = new Date(now);
targetDate.setFullYear(
now.getFullYear() + timeDelta.years || now.getFullYear(),
);
targetDate.setMonth(now.getMonth() + timeDelta.months || now.getMonth());
targetDate.setDate(now.getDate() + timeDelta.days || now.getDate());
targetDate.setHours(now.getHours() + timeDelta.hours || now.getHours());
targetDate.setMinutes(
now.getMinutes() + timeDelta.minutes || now.getMinutes(),
);
targetDate.setSeconds(
now.getSeconds() + timeDelta.seconds || now.getSeconds(),
);
const formattedDate = formatter.format(targetDate).replace(/\D/g, ".");
return { targetDate, formattedDate };
};
const getElapsedTime = (date: number) => {
const now = Date.now();
const elapsedSeconds = Math.floor((now - date) / 1000);
const elapsedMinutes = Math.floor(elapsedSeconds / 60);
const elapsedHours = Math.floor(elapsedMinutes / 60);
const elapsedDays = Math.floor(elapsedHours / 24);
const elapsedMonths = Math.floor(elapsedDays / 30);
const elapsedYears = Math.floor(elapsedDays / 365);
return {
elapsedSeconds,
elapsedMinutes,
elapsedHours,
elapsedDays,
elapsedMonths,
elapsedYears,
};
};
const elapsedTimeToString = (rest: {
elapsedSeconds: number;
elapsedMinutes: number;
elapsedHours: number;
elapsedDays: number;
elapsedMonths: number;
elapsedYears: number;
}) => {
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
switch (true) {
case rest.elapsedYears >= 1:
return rtf.format(-rest.elapsedYears, "year");
case rest.elapsedMonths >= 1:
return rtf.format(-rest.elapsedMonths, "month");
case rest.elapsedDays >= 1:
return rtf.format(-rest.elapsedDays, "day");
case rest.elapsedHours >= 1:
return rtf.format(-rest.elapsedHours, "hour");
case rest.elapsedMinutes >= 1:
return rtf.format(-rest.elapsedMinutes, "minute");
default:
return rtf.format(-rest.elapsedSeconds, "second");
}
};
export const getRelativeTime = (date: number) => {
const { elapsedDays, ...rest } = getElapsedTime(date);
if (elapsedDays > 90) {
return { expiresIn: "Expired", elapsedTime: "" };
} else Eif (elapsedDays === 90) {
return { expiresIn: "Expires today", elapsedTime: "" };
} else if (elapsedDays >= 83) {
return {
expiresIn: `Expires in ${90 - elapsedDays} days`,
elapsedTime: "",
};
}
const result = elapsedTimeToString({ elapsedDays, ...rest });
return { expiresIn: "", elapsedTime: result };
};
const calculateDate = () => {
return new Intl.DateTimeFormat("it-IT", {
year: "numeric",
month: "2-digit",
day: "2-digit",
formatMatcher: "best fit",
})
.format(Date.now())
.replace(/\D/g, ".");
};
export const checkEnd = (
startsAt: number | null | undefined,
endAt: number | null,
includeTime?: boolean | null,
): number => {
if (endAt) {
return endAt * 1000;
}
if (startsAt) {
// Timed single-date events store the event instant in startsAt (endsAt is
// null). After that instant the event is over. Date-only events use the
// end of that calendar day in ET, not the browser's local midnight.
if (includeTime) {
return startsAt * 1000;
}
return moment.unix(startsAt).tz(PLATFORM_TIMEZONE).endOf("day").valueOf();
}
return 0;
};
type TimeStampFormaterType = {
hour?: boolean;
timeZone?: boolean;
hours12Format?: boolean;
};
export const useTimestampToFormattedString = () => {
const { formatInTimezone } = useFormatDateInTimezone();
const timestampToFormattedString = (
timestamp: number,
options: TimeStampFormaterType = {
hour: false,
timeZone: false,
hours12Format: false,
},
customParser?: string,
) => {
const date = new Date(timestamp);
let parser = "MMMM d yyyy";
if (options.hour) {
if (options.hours12Format) {
parser += ", h:mm a";
} else {
parser += ", HH:mm";
}
}
const formattedDate = formatInTimezone(date, customParser || parser);
return options.timeZone ? `${formattedDate} ET` : `${formattedDate}`;
};
return { timestampToFormattedString };
};
export function getPeriodText(
startDate?: string | null,
endDate?: string | null,
) {
if (!startDate || !endDate) {
return "All time";
}
const start = new Date(startDate);
const end = new Date(endDate);
if (isNaN(start.getTime()) || isNaN(end.getTime())) {
return "All time";
}
const diffInMilliseconds = Math.abs(end.getTime() - start.getTime());
const diffInDays = diffInMilliseconds / (1000 * 60 * 60 * 24);
const diffInWeeks = diffInDays / 7;
const diffInMonths = diffInDays / 30.44; // Average number of days in a month
const diffInYears = diffInDays / 365.25; // Average number of days in a year
if (diffInYears >= 1) {
return `${Math.round(diffInYears)} year(s)`;
} else if (diffInMonths >= 1) {
return `${Math.round(diffInMonths)} month(s) `;
} else if (diffInWeeks >= 1) {
return `${Math.round(diffInWeeks)} week(s) `;
} else {
return `${Math.round(diffInDays)} day(s) `;
}
}
export const formatToUTC = (
date: Date | string | number,
format = "MM/dd/yyyy",
timezone = "UTC",
) => {
if (!date) return null;
Iif (date.toString() === "Invalid Date") return date;
if (["string", "object"].includes(typeof date)) {
return formatInTimeZone(new Date(date), timezone || "UTC", format);
}
return formatInTimeZone(+date * 1000, timezone || "UTC", format);
};
export const useUnixInTimezone = () => {
const unixInTimezone = (dateStr: string, timezone?: string) => {
return moment
.tz(dateStr, "UTC")
.tz(timezone || PLATFORM_TIMEZONE)
.unix();
};
return { unixInTimezone, currentTimezone: PLATFORM_TIMEZONE };
};
export const useFormatDateInTimezone = () => {
const formatInTimezone = (
date: Date | string | number,
format = "MM/dd/yyyy",
) => formatToUTC(date, format, PLATFORM_TIMEZONE);
return { formatInTimezone, currentTimezone: PLATFORM_TIMEZONE };
};
export const usePreciseTimeFormat = () => {
// Get the formatInTimezone utility and the current timezone from your existing hook
const { formatInTimezone, currentTimezone } = useFormatDateInTimezone();
/**
* Helper function to check if a date is "today" in a specific timezone.
* This needs to compare dates after converting them to the target timezone's local representation.
* @param dateToCheck The date to evaluate.
* @param referenceDate The date representing "now" or "today" in the target timezone.
*/
const isTodayInTimezone = (
dateToCheck: Date,
referenceDate: Date,
): boolean => {
return (
dateToCheck.getDate() === referenceDate.getDate() &&
dateToCheck.getMonth() === referenceDate.getMonth() &&
dateToCheck.getFullYear() === referenceDate.getFullYear()
);
};
/**
* Helper function to check if a date is "yesterday" in a specific timezone.
* @param dateToCheck The date to evaluate.
* @param referenceDate The date representing "now" or "today" in the target timezone.
*/
const isYesterdayInTimezone = (
dateToCheck: Date,
referenceDate: Date,
): boolean => {
const yesterdayRef = new Date(referenceDate);
yesterdayRef.setDate(referenceDate.getDate() - 1); // Mutates, so ensure referenceDate isn't directly reused
return isTodayInTimezone(dateToCheck, yesterdayRef); // Reuse isToday logic
};
const formatPreciseTime = (
dateInput: Date | string | number,
fallback?: string,
): string => {
const targetDate = toDate(dateInput);
// If targetDate is invalid, return fallback
Iif (isNaN(targetDate.getTime())) {
return fallback || dateInput.toString();
}
const nowInTargetTimezone = new Date(
new Date().toLocaleString("en-US", { timeZone: currentTimezone }),
);
const targetDateInTargetTimezone = new Date(
targetDate.toLocaleString("en-US", { timeZone: currentTimezone }),
);
Iif (isTodayInTimezone(targetDateInTargetTimezone, nowInTargetTimezone)) {
// If today, use formatInTimezone with the time format
return formatInTimezone(targetDate, "h:mm a")?.toString() || "";
} else Iif (
isYesterdayInTimezone(targetDateInTargetTimezone, nowInTargetTimezone)
) {
// If yesterday, use formatInTimezone with the "Yesterday" format
return "Yesterday";
} else {
// Otherwise, use formatInTimezone with the month/day/time format
return formatInTimezone(targetDate, "M/d h:mm a")?.toString() || "";
}
};
return { formatPreciseTime, isTodayInTimezone, isYesterdayInTimezone };
};
export const useDayLabelFromTimestamp = () => {
const { currentTimezone } = useFormatDateInTimezone();
const { isTodayInTimezone, isYesterdayInTimezone } = usePreciseTimeFormat();
const getDayLabelFromTimestamp = (timestamp: number): string => {
const targetDate = toDate(timestamp * 1000);
const now = new Date(
new Date().toLocaleString("en-US", { timeZone: currentTimezone }),
);
const target = new Date(
targetDate.toLocaleString("en-US", { timeZone: currentTimezone }),
);
Iif (isTodayInTimezone(target, now)) return "Today";
Iif (isYesterdayInTimezone(target, now)) return "Yesterday";
return format(target, "MMM dd, yyyy");
};
return { getDayLabelFromTimestamp };
};
export function getUtcTimestampFromDate({
dateString,
timeString = "12:00 AM",
dateFormat = "MM/DD/YYYY",
timeFormat = "hh:mm A",
useStrictFormat = true,
}: {
dateString: string | Date;
timeString?: string;
dateFormat?: string;
timeFormat?: string;
useStrictFormat?: boolean;
}) {
if (!dateString) return "";
if (typeof dateString === "string") {
if (useStrictFormat) {
const combinedDateTime = `${dateString} ${timeString}`;
const utcMoment = moment.utc(
combinedDateTime,
`${dateFormat} ${timeFormat}`,
);
return utcMoment.unix();
} else {
return moment.utc(dateString).unix();
}
} else if (typeof dateString !== "string" && !!timeString) {
const formattedUTCDate = moment.utc(dateString).format(dateFormat);
return getUtcTimestampFromDate({
dateString: formattedUTCDate,
timeString,
});
} else {
return moment(dateString).utc().unix();
}
}
export const CANARY_TZ = "Atlantic/Canary";
const DEFAULT_FORMAT = "MM/DD/YYYY";
export const formatInUTCMoment = (
value?: number | string | Date | null,
format = DEFAULT_FORMAT,
useMs?: boolean,
) => {
if (!value) return "";
if (typeof value === "string") {
// ISO "YYYY-MM-DD" from the new BE date.Date type — reformat to the
// requested display format (e.g. "01/05/1990" for DEFAULT_FORMAT).
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
return moment.utc(value).format(format);
}
// Legacy: string already in the requested display format — pass through.
Eif (format === DEFAULT_FORMAT) return value;
}
if (typeof value === "number" && value) {
//moment.unix() expects the number to be in seconds
//moment.utc() expects the number to be in miliseconds
//in order to use the right method, we need to determine whether the number provided is in seconds or miliseconds
const nowInSeconds = moment().unix();
const isSeconds = value < nowInSeconds * 1.5; //check if its second or ms, with some offset to make up for possible fuutre time
if (!useMs || isSeconds) return moment.unix(value).utc().format(format);
else Ereturn moment.utc(value).format(format);
}
return moment.utc(value).format(format);
};
export const formatInCanaryMoment = (
value?: number | string | Date | null,
format = DEFAULT_FORMAT,
useMs?: boolean,
) => {
Iif (!value) return "";
Iif (typeof value === "string" && format === DEFAULT_FORMAT) return value;
Eif (typeof value === "number") {
const nowInSeconds = moment().unix();
const isSeconds = value < nowInSeconds * 1.5;
Eif (!useMs || isSeconds) {
return moment.unix(value).tz(CANARY_TZ).format(format);
}
return moment.tz(value, CANARY_TZ).format(format);
}
return moment(value).tz(CANARY_TZ).format(format);
};
export const getUTCDefaultValue = (val: any, useUTCMoment?: boolean) => {
if (!!val && typeof val === "string" && useUTCMoment) {
return moment.utc(val);
} else return val;
};
export const getMomentDate = (date: Date) => {
return moment([date.getFullYear(), date.getMonth(), date.getDate()]);
};
/**
* Converts a date value from a form picker (Date object) or from the API
* (already a "YYYY-MM-DD" string) to an ISO-8601 date string for submission.
* Returns null for empty/null values.
*/
export const toISODateString = (
value: Date | string | null | undefined,
): string | null => {
if (!value) return null;
if (typeof value === "string") {
// Already ISO YYYY-MM-DD — return unchanged
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return value;
// Other string format (e.g. "04/02/2026" MM/DD/YYYY from old API, or
// "Thu Apr 02 2026 03:00:00 GMT+0300" from Date.toString()) — parse via
// moment which handles both, then extract LOCAL calendar date.
const parsed = moment(value);
Iif (!parsed.isValid()) return null;
return [
parsed.year(),
String(parsed.month() + 1).padStart(2, "0"),
String(parsed.date()).padStart(2, "0"),
].join("-");
}
// Date object from picker: use LOCAL year/month/day so the calendar date the
// user picked is preserved regardless of UTC offset (e.g. UTC+3 user picking
// April 2 gets local midnight = UTC April 1 21:00 — moment.utc() would give
// the wrong date; local components give the correct date).
return [
value.getFullYear(),
String(value.getMonth() + 1).padStart(2, "0"),
String(value.getDate()).padStart(2, "0"),
].join("-");
};
/**
* Parses a "YYYY-MM-DD" ISO date string into a local-midnight Date so the
* calendar date is preserved in the date picker regardless of the user's UTC
* offset (unlike `new Date("YYYY-MM-DDT00:00:00Z")` which creates UTC midnight
* and shows the previous day to UTC− users such as all US timezones).
*/
export const isoStringToLocalDate = (str: string): Date => {
const [y, m, d] = str.split("-").map(Number);
return new Date(y, m - 1, d);
};
export const getUTCRangeFromTimezone = (
startDate: string,
endDate: string,
timezone: string,
) => {
// Parse the start date string and apply the "start of day" logic (0:0:0)
const localStartDate = parse(startDate, "yyyy-MM-dd", new Date());
localStartDate.setHours(0, 0, 0, 0);
// Parse the end date string and apply the "end of day" logic (23:59:59)
const localEndDate = parse(endDate, "yyyy-MM-dd", new Date());
localEndDate.setHours(23, 59, 59, 999);
// Convert the zoned start date to its UTC equivalent
const utcStartDate = moment(zonedTimeToUtc(localStartDate, timezone))
.utc()
.format("YYYY-MM-DD");
// Convert the zoned end date to its UTC equivalent
const utcEndDate = moment(zonedTimeToUtc(localEndDate, timezone))
.utc()
.format("YYYY-MM-DD");
return {
start: utcStartDate,
end: utcEndDate,
};
};
export const getFormattedTimezoneRange = (
days: number,
timezone: string,
): { dateString: string; startDate: Date; endDate: Date } => {
const endOfTodayInTimezone = moment().tz(timezone).endOf("day");
const startOfRangeInTimezone = endOfTodayInTimezone
.clone()
.subtract(days - 1, "days")
.startOf("day");
const startDateObject = startOfRangeInTimezone.toDate();
const endDateObject = endOfTodayInTimezone.toDate();
// Format the start and end dates as strings
const startDate = startOfRangeInTimezone.format("MM/DD/YYYY");
const endDate = endOfTodayInTimezone.format("MM/DD/YYYY");
// If the range is a single day, return a single date string
if (days === 1) {
return {
dateString: startDate,
startDate: startDateObject,
endDate: endDateObject,
};
}
// Otherwise, return a date range string
return {
dateString: `${startDate}-${endDate}`,
startDate: startDateObject,
endDate: endDateObject,
};
};
export const formatHoldPeriod = (holdingUntilAt: number): string => {
const holdingUntil = moment.unix(holdingUntilAt);
const now = moment();
const duration = moment.duration(holdingUntil.diff(now));
if (duration.asMilliseconds() < 0) {
return "< 1 hour";
}
const days = Math.floor(duration.asDays());
const hours = Math.floor(duration.asHours());
if (days >= 1) {
return `${days} ${days === 1 ? "day" : "days"}`;
} else if (hours >= 1) {
return `${hours} ${hours === 1 ? "hour" : "hours"}`;
} else {
return "< 1 hour";
}
};
|