All files / src/utils/common/dates renderTimestamp.ts

0% Statements 0/10
100% Branches 0/0
0% Functions 0/1
0% Lines 0/9

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                                                                           
/**
 * Renders a UNIX timestamp as a formatted date and time string in the format 'YYYY-MM-DD HH:mm:ss'.
 *
 * @param {number} timestamp - The UNIX timestamp to be rendered.
 * @return {string} The formatted date and time string.
 */
export const renderTimestamp = (timestamp: number): string => {
  // Create a Date object from the UNIX timestamp (timestamp is assumed to be in seconds)
  const date = new Date(timestamp * 1000);
 
  // Use Intl.DateTimeFormat for formatting the date
  // Customize options as needed to match the desired format 'YYYY-MM-DD HH:mm:ss'
  const options: any = {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
    hour12: false,
  };
 
  // Create an Intl.DateTimeFormat instance with the desired options and locale ('en-US' used here as an example)
  const formatter = new Intl.DateTimeFormat("en-US", options);
 
  // Format the date
  const formattedDate = formatter.format(date);
 
  // Since Intl.DateTimeFormat returns the date in the format 'MM/DD/YYYY, HH:mm:ss' for 'en-US' locale,
  // we need to rearrange the formatted string to match 'YYYY-MM-DD HH:mm:ss'
  const parts = formattedDate.split(", ");
  const datePart = parts[0].split("/");
  const timePart = parts[1];
 
  // Rearrange and format the string
  return `${datePart[2]}-${datePart[0]}-${datePart[1]} ${timePart}`;
};