import { __ } from '@wordpress/i18n'; import { currentLocale } from './locale'; import { JUST_NOW_SECONDS, MILLISECONDS_PER_SECOND, SECONDS_PER_DAY, SECONDS_PER_HOUR, SECONDS_PER_MINUTE, } from './timeUnits'; function secondsSince( isoTime: string, now: number ): number { const elapsedMilliseconds = now - Date.parse( isoTime ); return Math.max( 0, Math.round( elapsedMilliseconds / MILLISECONDS_PER_SECOND ) ); } function relativeText( seconds: number ): string { const relativeFormat = new Intl.RelativeTimeFormat( currentLocale(), { numeric: 'always', } ); if ( seconds < SECONDS_PER_HOUR ) { const minutes = Math.max( 1, Math.round( seconds / SECONDS_PER_MINUTE ) ); return relativeFormat.format( -minutes, 'minute' ); } if ( seconds < SECONDS_PER_DAY ) { return relativeFormat.format( -Math.round( seconds / SECONDS_PER_HOUR ), 'hour' ); } return relativeFormat.format( -Math.round( seconds / SECONDS_PER_DAY ), 'day' ); } export function timeAgo( isoTime: string | null, now: number ): string { if ( isoTime === null || isoTime === '' ) { return __( 'never', 'aiplaz-link-checkup' ); } const seconds = secondsSince( isoTime, now ); if ( seconds < JUST_NOW_SECONDS ) { return __( 'just now', 'aiplaz-link-checkup' ); } return relativeText( seconds ); } export function timeAgoSentence( isoTime: string | null, now: number ): string { const text = timeAgo( isoTime, now ); const firstLetter = text.charAt( 0 ).toLocaleUpperCase( currentLocale() ); return firstLetter + text.slice( 1 ); } export function dayAndMonth( isoTime: string | null ): string { if ( isoTime === null || isoTime === '' ) { return ''; } return new Intl.DateTimeFormat( currentLocale(), { day: 'numeric', month: 'long', } ).format( new Date( isoTime ) ); }