1- import { isString } from '@guardian/libs' ;
1+ import { isString , isUndefined } from '@guardian/libs' ;
22import { getEditionFromId } from '../lib/edition' ;
33import { useConfig } from './ConfigContext' ;
44import { Island } from './Island' ;
@@ -14,11 +14,11 @@ type Props = {
1414type DisplayProps =
1515 | {
1616 display ?: 'absolute' ;
17- absoluteServerTimes ?: never ;
17+ serverTime ?: never ;
1818 }
1919 | {
2020 display : 'relative' ;
21- absoluteServerTimes : boolean ;
21+ serverTime ?: number ;
2222 } ;
2323
2424const formatWeekday = ( date : Date , locale : string , timeZone : string ) =>
@@ -49,31 +49,35 @@ const formatTime = (date: Date, locale: string, timeZone: string) =>
4949 . replace ( ':' , '.' ) ;
5050
5151const ONE_MINUTE = 60_000 ;
52- /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date */
5352const MAX_DATE = 8.64e15 ;
54- /** Rounded down to the previous minute, to ensure relative times rarely go backwards */
55- const getServerTime = ( ) => Math . floor ( Date . now ( ) / ONE_MINUTE ) * ONE_MINUTE ;
5653
5754export const DateTime = ( {
5855 date,
5956 showWeekday,
6057 showDate,
6158 showTime,
6259 display = 'absolute' ,
63- absoluteServerTimes = true ,
60+ serverTime ,
6461} : Props & DisplayProps ) => {
6562 const { editionId } = useConfig ( ) ;
6663 const { dateLocale, timeZone } = getEditionFromId ( editionId ) ;
6764
65+ /**
66+ * Server time (if set) is rounded down to the previous minute to ensure
67+ * relative times rarely go backwards. If unset we use the maximum value
68+ * that can be represented by a `Date` object [1] to force display as an
69+ * absolute date due to `then` being far in the past.
70+ *
71+ * [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date
72+ */
73+ const now = isUndefined ( serverTime )
74+ ? MAX_DATE
75+ : Math . floor ( serverTime / ONE_MINUTE ) * ONE_MINUTE ;
6876 const then = date . getTime ( ) ;
6977
7078 return display === 'relative' ? (
7179 < Island priority = "enhancement" defer = { { until : 'visible' } } >
72- < RelativeTime
73- then = { then }
74- now = { absoluteServerTimes ? MAX_DATE : getServerTime ( ) }
75- editionId = { editionId }
76- />
80+ < RelativeTime then = { then } now = { now } editionId = { editionId } />
7781 </ Island >
7882 ) : (
7983 < time
0 commit comments