1+ import { useLocalStorage , StorageKeys } from "@/common/localStorage" ;
12import dayjs from "dayjs" ;
23import duration from "dayjs/plugin/duration" ;
34dayjs . extend ( duration ) ;
45
6+ export const [ timeFormat , setTimeFormat ] = useLocalStorage < "12hr" | "24hr" > (
7+ StorageKeys . TIME_FORMAT ,
8+ "24hr" ,
9+ true
10+ ) ;
11+
512// Weeks are not working as intended. update package when this gets merged.
613// https://github.com/iamkun/dayjs/pull/2811
714
815// make a function where if the number is less than 10, it will add a 0 in front of it
16+
917function pad ( num : number ) {
1018 return num < 10 ? `0${ num } ` : num ;
1119}
@@ -14,28 +22,42 @@ function pad(num: number) {
1422export function formatTimestamp ( timestamp : number , seconds = false ) {
1523 const date = new Date ( timestamp ) ;
1624 const today = new Date ( ) ;
17-
1825 const yesterday = new Date ( ) ;
1926 yesterday . setDate ( yesterday . getDate ( ) - 1 ) ;
2027
2128 const sameYear = today . getFullYear ( ) === date . getFullYear ( ) ;
29+ const format = timeFormat ( ) ;
30+
31+ const hours = date . getHours ( ) ;
32+ const minutes = pad ( date . getMinutes ( ) ) ;
33+ const secondsText = seconds ? `:${ pad ( date . getSeconds ( ) ) } ` : "" ;
34+
35+ let formattedHours : string | number = hours ;
36+ let ampm = "" ;
37+
38+ if ( format === "12hr" ) {
39+ ampm = hours >= 12 ? " PM" : " AM" ;
40+ formattedHours = hours % 12 || 12 ;
41+ }
42+
43+ if ( format === "24hr" ) {
44+ formattedHours = pad ( hours ) ;
45+ }
2246
2347 if (
2448 sameYear &&
2549 date . getDate ( ) === today . getDate ( ) &&
2650 date . getMonth ( ) === today . getMonth ( )
2751 ) {
28- return `${ pad ( date . getHours ( ) ) } :${ pad ( date . getMinutes ( ) ) } ${
29- seconds ? `:${ pad ( date . getSeconds ( ) ) } ` : ""
30- } `;
52+ return `${ formattedHours } :${ minutes } ${ secondsText } ${ ampm } ` ;
3153 } else if ( sameYear && yesterday . toDateString ( ) === date . toDateString ( ) ) {
32- return `Yesterday at ${ pad ( date . getHours ( ) ) } :${ pad ( date . getMinutes ( ) ) } ` ;
54+ return `Yesterday at ${ formattedHours } :${ minutes } ${ ampm } ` ;
3355 } else {
3456 return `${ Intl . DateTimeFormat ( "en-GB" , {
3557 day : "2-digit" ,
3658 month : "short" ,
3759 year : "numeric" ,
38- } ) . format ( date ) } at ${ pad ( date . getHours ( ) ) } :${ pad ( date . getMinutes ( ) ) } `;
60+ } ) . format ( date ) } at ${ formattedHours } :${ minutes } ${ ampm } `;
3961 }
4062}
4163
@@ -59,7 +81,6 @@ export const fullDateTime = (timestamp: number) => {
5981 ) } `;
6082} ;
6183
62- // get days ago from timestamp
6384export function getDaysAgo ( timestamp : number ) {
6485 const rtf = new Intl . RelativeTimeFormat ( "en" , {
6586 numeric : "auto" ,
@@ -287,3 +308,4 @@ function pluralize(
287308 count + " " + ( count > 1 ? `${ word } s` : word + ( suffix ? ` ${ suffix } ` : "" ) )
288309 ) ;
289310}
311+
0 commit comments