Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function timestampToWords(timestamp) {
- // Convert timestamp to milliseconds
- let milliseconds = timestamp * 1000;
- // Create a new Date object
- let date = new Date(milliseconds);
- // Get the current date
- let currentDate = new Date();
- currentDate.setHours(0, 0, 0, 0); // Reset hours, minutes, seconds, and milliseconds for comparison
- // Get the parts of the date
- let year = date.getFullYear();
- let month = date.getMonth() + 1; // Months are zero-indexed, so we add 1
- let day = date.getDate();
- let hours = date.getHours();
- let minutes = date.getMinutes();
- // Check if the date is today, tomorrow, or later
- let dateString;
- if (date.toDateString() === currentDate.toDateString()) {
- dateString = 'today';
- } else {
- let diff = (date - currentDate) / (1000 * 60 * 60 * 24);
- if (diff <= 1) {
- dateString = 'tomorrow';
- } else {
- dateString = `${year}-${month < 10 ? '0' : ''}${month}-${day < 10 ? '0' : ''}${day}`;
- }
- }
- // Construct the human-readable string
- if (dateString === 'today' || dateString === 'tomorrow') {
- return dateString;
- } else {
- return `${dateString} ${hours < 10 ? '0' : ''}${hours}:${minutes < 10 ? '0' : ''}${minutes}`;
- }
- }
- // Example usage
- let timestamp = 1615804800; // Example timestamp for March 15, 2021 (today)
- console.log(timestampToWords(timestamp)); // Output: "today"
- timestamp = 1615891200; // Example timestamp for March 16, 2021 (tomorrow)
- console.log(timestampToWords(timestamp)); // Output: "tomorrow"
- timestamp = 1615977600; // Example timestamp for March 17, 2021
- console.log(timestampToWords(timestamp)); // Output: "2021-03-17 00:00"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement