timestamp.ts raw

   1  import dayjs from 'dayjs'
   2  import relativeTime from 'dayjs/plugin/relativeTime'
   3  
   4  dayjs.extend(relativeTime)
   5  
   6  /**
   7   * Format a unix timestamp (seconds) to a relative time string.
   8   * e.g., "5 minutes ago", "2 hours ago", "3 days ago"
   9   */
  10  export function formatTimestamp(timestamp: number): string {
  11    return dayjs.unix(timestamp).fromNow()
  12  }
  13  
  14  /**
  15   * Format a unix timestamp to a short time string.
  16   * Shows time for today, date for older messages.
  17   */
  18  export function formatMessageTime(timestamp: number): string {
  19    const date = dayjs.unix(timestamp)
  20    const now = dayjs()
  21  
  22    if (date.isSame(now, 'day')) {
  23      return date.format('HH:mm')
  24    } else if (date.isSame(now, 'year')) {
  25      return date.format('MMM D')
  26    } else {
  27      return date.format('MMM D, YYYY')
  28    }
  29  }
  30