Advertisement
Guest User

Untitled

a guest
Mar 15th, 2024
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.74 KB | Source Code | 0 0
  1. function timestampToWords(timestamp) {
  2.     // Convert timestamp to milliseconds
  3.     let milliseconds = timestamp * 1000;
  4.  
  5.     // Create a new Date object
  6.     let date = new Date(milliseconds);
  7.  
  8.     // Get the current date
  9.     let currentDate = new Date();
  10.     currentDate.setHours(0, 0, 0, 0); // Reset hours, minutes, seconds, and milliseconds for comparison
  11.  
  12.     // Get the parts of the date
  13.     let year = date.getFullYear();
  14.     let month = date.getMonth() + 1; // Months are zero-indexed, so we add 1
  15.     let day = date.getDate();
  16.     let hours = date.getHours();
  17.     let minutes = date.getMinutes();
  18.  
  19.     // Check if the date is today, tomorrow, or later
  20.     let dateString;
  21.     if (date.toDateString() === currentDate.toDateString()) {
  22.         dateString = 'today';
  23.     } else {
  24.         let diff = (date - currentDate) / (1000 * 60 * 60 * 24);
  25.         if (diff <= 1) {
  26.             dateString = 'tomorrow';
  27.         } else {
  28.             dateString = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;
  29.         }
  30.     }
  31.  
  32.     // Construct the human-readable string
  33.     if (dateString === 'today' || dateString === 'tomorrow') {
  34.         return dateString;
  35.     } else {
  36.         return `${dateString} ${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}`;
  37.     }
  38. }
  39.  
  40. // Example usage
  41. let timestamp = 1615804800; // Example timestamp for March 15, 2021 (today)
  42. console.log(timestampToWords(timestamp)); // Output: "today"
  43.  
  44. timestamp = 1615891200; // Example timestamp for March 16, 2021 (tomorrow)
  45. console.log(timestampToWords(timestamp)); // Output: "tomorrow"
  46.  
  47. timestamp = 1615977600; // Example timestamp for March 17, 2021
  48. console.log(timestampToWords(timestamp)); // Output: "2021-03-17 00:00"
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement