Javascript tells the time difference between 1 minute and 1 minutes. A timer is set up to notify when the time is

self.calculateMessageTime = function calculateMessageTime(receiveDate){
    var dateReceived = Date.parse(receiveDate);
    var now = new Date();
    now = Date.now();

    // in seconds
    var difference = Math.abs(dateReceived - now)/1000;
    if(difference < 60) {
        return "1 minute ago";
    }else if(difference < (60*60) ) {
        // minutes
        return Math.floor(difference/60) + " minutes ago";

    } else if(difference < (60*60*24)) {
        // hours
        var hoursPassed = Math.floor(difference/60/60) + " hours ago";
        if(hoursPassed !== "1 hours ago") {
            return Math.floor(difference/60/60) + " hours ago";
        } else {
            return Math.floor(difference/60/60) + " hour ago";
        }
    } else if(difference < (60*60*24*7)) {
        // days
        var daysPassed = Math.floor(difference/24/60/60) + " days ago";
        if(daysPassed !== "1 days ago") {
            return Math.floor(difference/24/60/60) + " days ago";
        } else {
            return Math.floor(difference/24/60/60) + " day ago";
        }

    } else if(difference < (60*60*24*7*4)) {
        // weeks
        var weeksPassed = Math.floor(difference/7/24/60/60) + " weeks ago";
        if(weeksPassed !== "1 weeks ago") {
            return Math.floor(difference/7/24/60/60) + " weeks ago";
        } else {
            return Math.floor(difference/7/24/60/60) + " week ago";
        }
    } else {
        var monthsPassed = Math.floor(difference/4/7/24/60/60) + " months ago";
        if(monthsPassed !== "1 months ago") {
            return Math.floor(difference/4/7/24/60/60) + " months ago";
        } else {
            return Math.floor(difference/4/7/24/60/60) + " month ago";
        }
    }
};

The method above is designed to display a message indicating how long ago a notification was received on the UI. For example, "1 minute ago" or "1 day ago", and increment accordingly.

Currently, it correctly returns "1 minute ago," but at the exactly 60-second mark, I receive "1 minutes ago." This issue also occurs with day(s).

I suspect the problem may be due to comparing against 60 seconds when it should be 59? I'm quite puzzled by this. Any assistance would be greatly appreciated.

Answer №1

This is the way to achieve it

const calculateTimeDifference = targetDate => {
  const date = new Date(targetDate).getTime();
  let now = new Date().getTime();
  const difference = Math.abs(date - now) / 1000
  const minutes = Math.floor(difference/60) % 60 || ''
  const hours = Math.floor(difference/60/60) % 24 || ''
  const days = Math.floor(difference/60/60/24) % 24 || ''
  const weeks = Math.floor(difference/60/60/24/7)|| ''
  const months = Math.floor(difference/4/7/24/60/60) || ''
  return `${months ? months + 'months' : ''} ${weeks ? weeks + 'weeks' : ''} ${days ? days + 'days' : ''} ${days ? days + 'days' : ''} ${hours ? hours + 'hours' : ''} ${minutes ? minutes + 'mins' : ''} `.replace(/\b(1\D+?)s/g, '$1').trim()
}

console.log(calculateTimeDifference('2017/02/27 18:22'))
console.log(calculateTimeDifference(new Date().getTime() - 60 * 1000 - 5000))

The key aspect of this script is .replace(/\b(1\D+?)s/g, '$1') This will substitute all instances of 1 thing with 1 thing or any other variations such as .replace(/(0\D+?)s\s*/g, ''). You just need to format the string like '1days 0hours 0minutes'

console.log('11mounths 1days 0hours 20minutes'.replace(/\b0\D+?s\s*/g, '').replace(/\b(1\D+?)s/g, '$1'))

Answer №2

function calculateMessageAge(timestamp) {
  var date = Date.parse(timestamp);
  var now = Date.now();
  // in seconds
  var difference = Math.abs(date - now) / 1000;
  var minute = 60;
  var hour = 60 * minute;
  var day = 24 * hour;
  var week = 7 * day;
  var month = 4 * week; 
  var number;
  var label;

  if (difference > month) {
    number = Math.floor(difference / month);
    label = number + ' month' + (number > 1 ? 's': '');
  } else if (difference > week) {
    number = Math.floor(difference / week);
    label = number + ' week' + (number > 1 ? 's': '');
  } else if (difference > day) {
    number = Math.floor(difference / day);
    label = number + ' day' + (number > 1 ? 's': '');
  } else if (difference > hour) {
    number = Math.floor(difference / hour);
    label = number + ' hour' + (number > 1 ? 's': '');
  } else if (difference > minute) {
    number = Math.floor(difference / minute);
    label = number + ' min' + (number > 1 ? 's': '');
  } else {
    label = '1 min';
  }

  return label;
};

console.log(calculateMessageAge('02-02-2018'));
console.log(calculateMessageAge('01-01-2018 20:00'));
console.log(calculateMessageAge(new Date(new Date().getTime() - 60 * 1000)));
console.log(calculateMessageAge(new Date(new Date().getTime() - 59 * 1000)));
console.log(calculateMessageAge(new Date(new Date().getTime() - 60 * 60 * 4 * 1000)));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to limit a slash command to only be accessible to those with specific roles on a Discord server?

I am currently working on a discord bot using Discord.js V14 and implementing a command called "claimticket". However, I am facing an issue where I need to restrict this command to only members who possess one of the two specific roles that I have mentione ...

What steps can I take to resolve the CSP errors I am experiencing?

I am currently working with NextJs@12 and I am attempting to set up CSP for my application. Unfortunately, I keep encountering errors in my console and I cannot figure out where I am going wrong. Below is the current policy that I have in my next.config fi ...

Create a typing effect in Javascript that mimics the user's input

Trying to simulate a typing effect with the sentence extracted from user input using JavaScript, but encountering some issues. Successfully capturing and displaying the input in the console with console.log(), however, incorporating the typing effect func ...

Submit a form using jQuery when it is being loaded via AJAX using jQuery

Looking for help with posting a form using jQuery.post: Here is the JavaScript function I am using: function post_ajax_form2(url,formId,message){ bsendMessage = 0; if (typeof message !== 'undefined') { bsendMessage = 1;} var data = ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

What is the method for obtaining the size of a mesh object in pixels (instead of Vector3) within BabylonJS?

Exploring Babylon.js How can I retrieve the size of a mesh object in pixels instead of Vector3 in a React application using Babylonjs? This is what I attempted: let meshPixelSize = meshObject.getBoundingInfo().boundingBox; ...

"Utilizing VueJS XHR functionality within a versatile and reusable component

Seeking advice on best practices for improving the following scenario: I have a single global reusable component called <MainMenu>. Within this component, I am making an XHR request to fetch menu items. If I place <MainMenu> in both the heade ...

Creating a dynamic table in AngularJS with rotating values for rows and columns

I am seeking assistance in creating a table with a custom number of rows and columns. The table should have two input fields for specifying the number of rows and columns, and upon submission, the table should dynamically adjust to display the specified nu ...

Learn how to incorporate additional rows into a table by pressing the plus button within the table with the help of Angular

I require some assistance. I am looking to dynamically generate a row after clicking on the plus button using angular.js. The newly created row should contain an ID and model generated dynamically. Here is an overview of my code: <table class="table ta ...

Issues with Toggling Visibility in HTML, CSS, and Javascript

Currently, I am working on a website and following a tutorial called "Creating Slideshow using HTML, CSS, and Javascript" by W3Schools. In the project, I want to hide the thumbnail images located at the bottom and the navigation arrows initially and have t ...

Only dispatch to props upon being clicked

I am encountering an issue with the mapDispatchToProps function being sent as a whole, rather than only when I click on the delete button. My class successfully fetches the list data and everything works as expected. However, upon adding the delete button ...

Combine similar JSON objects into arrays

I'm working with a dataset returned by a library, and it's structured like this: var givenData = [{"fName": "john"}, {"fName": "mike"}, {"country": "USA"}] My goal is to group the "fName" values together and add '[]' to achieve the fo ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...

Discover a foolproof method for effortlessly examining an flv or mp4 file embedded within a webpage simply by

I've encountered a challenge with JavaScript. I can successfully check a flash object in a webpage when hovering over it, but I'm unsure how to achieve the same for flv or mp4 objects when either hovering over or moving away from them. Currently ...

Fill the angular ui-bootstrap popover with content

Can anyone help me with populating an angular ui bootstrap popover? My goal is to populate the popover with a collection of actor names. Below is the code snippet: <div class="container" ng-if="radioModel=='Search for Actor'"> <p> ...

An error occurred due to a missing value within the forEach loop

In my JavaScript object, I am encountering an issue with a key. resolve: function () { var result = this.initialValue; console.log('initial value:',result); // 5 this.functions.forEach(function (element, index) { ...

I'm having trouble accessing my POST data using console.log. Instead of getting the expected data, all I see in the console when I try to GET is "

My code for the POST function is working, but when I try to retrieve and display the POST response from the server, all I get is "null". Can anyone help me figure out how to properly send data from my form to the server and then successfully console log it ...

ReactJS: error occurs when trying to fetch data and encountering issues with reading properties

I am currently attempting to initiate an API call (a GET request) in order to download a document. However, I am encountering an error when making the API call: TypeError: Cannot read properties of undefined (reading 'payload') const printPin ...

Rearrange div elements following an ajax request based on a data attribute and applying the .animate method

I am dealing with a collection of div elements, each assigned a unique numeric id and data-position in sequential order (1 for the first in the list, 2 for the second, and so on). Upon making an ajax call using jQuery, the response is a JSON object that r ...

What is the best way to access the current value and name of a textbox in real-time using

How can I retrieve the value of a textbox in JavaScript using onblur and on keyup events, while also performing real-time checking for each individual textbox using "this keyword"? Here is my JSFiddle link. Can you assist me in modifying it? ...