Time Ago Calculator inaccurately computes the months

Currently, I am encountering an issue with the angular-moment library where it interprets anything exceeding 25 days as a month when using amTimeAgo.

In the following demonstration, I utilize moment JS to calculate the time difference of 25, 26, and 27 days back from the current date. Subsequently, I employ the amTimeAgo function to determine the duration from the present moment.

angular.module('timeApp', ['angularMoment'])
.controller('mainController', [ '$scope', function($scope) {
  
   $scope.today = new Date();
   $scope.parsedToday = moment($scope.today).format('MM/DD/YYYY hh:mm A');
   $scope.days25FromNow = moment($scope.today).subtract({days: 25}).format('MM/DD/YYYY hh:mm A');
   $scope.days26FromNow = moment($scope.today).subtract({days: 26}).format('MM/DD/YYYY hh:mm A');
   $scope.days27FromNow = moment($scope.today).subtract({days: 27}).format('MM/DD/YYYY hh:mm A');
  
}]);
<!DOCTYPE html>
<html>

  <head>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0/angular.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.0/angular-moment.min.js"></script>

    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>
  
  <body>
    <div class="container" ng-app="timeApp" ng-controller="mainController as main">

      <div>
        <h2>AmTimeAgo Issue Beyond 25 Days</h2>
        <h3>Current Time: {{ parsedToday}}</h3>
        
        <p>25 Days Ago - {{days25FromNow}} <br>
          Original AM Time Ago -  {{days25FromNow | amTimeAgo}} <br>
          Expected Output - 25 days ago
        </p>

        <p>26 Days Ago - {{days26FromNow}} <br>
          Original AM Time Ago -  {{days26FromNow | amTimeAgo}}<br>
          Expected Output - 26 days ago
        </p>
        
        <p>27 Days Ago - {{days27FromNow}} <br>
          Original AM Time Ago -  {{days27FromNow | amTimeAgo}}<br>
          Expected Output - 27 days ago
        </p>        
      </div>
      
    </div>
  </body>

</html>

Identical Example on Plnkr - http://plnkr.co/edit/DZqqI5BC2XNrITThLCS7?p=preview

Is there a specific configuration that can be adjusted to make the calculation consider 30 days as a month? Or could this possibly be a bug? I have reviewed their documentation and source code, yet I am unable to locate where this threshold of 25 days can be modified to 30.

Thank you!

Answer №1

Your main concern lies in the warning generated by your code, as evident in both the snippet provided and the debug console within your Plunker example.

A deprecation warning is being triggered due to the input not adhering to a recognized ISO format. The fallback to js Date() by the moment construction poses reliability concerns across different browsers and versions. Non-ISO date formats are discouraged and will be eliminated in an upcoming major release. More information can be found at this link.

The value passed into the amTimeAgo filter serves as an argument for the moment(...) factory function. Therefore, avoid formatting it with a locale-specific structure.

Simply eliminate the .format('MM/DD/YYYY hh:mm A') from your daysXXFromNow fields to ensure proper rendering, passing a moment object instead.

To address your original query, the observed behavior aligns with predefined relative thresholds. According to default settings, a span of 26 to 45 days qualifies as a month. Further details are available here.

You have the flexibility to adjust these criteria based on preference by configuring the relative time thresholds, outlined here.

For instance, to extend the one-month threshold to 28 days, execute:

moment.relativeTimeThreshold('d', 28);

Note that defining the term "months" precisely presents challenges due to variations in the number of days per month. Additionally, the approximate nature of the fromNow functionality is deliberate.

If you seek an exact day count instead, utilize the diff method over the fromNow option.

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

If an array contains a property, add it to the object

I have a set of objects with unique identifiers, and there's also an array containing specific identifier values. I want to mark the objects that have an id matching any value in the array by adding a new property called found and setting it to true. ...

Clear the ant design RangeSelect value once it is closed

When I open the ant design range select and navigate to a previous date, then close it without selecting any date or year, upon reopening it still displays the previously navigated date. I would like the current date to be displayed whenever I open the ra ...

Wait for a reply from one GET request before initiating the next one in node

When working with node, I am making two consecutive calls to an API. My goal is to ensure that the first GET request has completed before triggering the second one, using data from the response of the first call. To achieve this, I have experimented with ...

Use ag-Grid to customize your column headers with checkboxes, allowing you to easily select or deselect all items in that column. This feature is not limited to

In my experience with ag-grid, I often find myself needing to customize the first column header to include a checkbox. This allows me to easily perform actions such as selecting all or deselecting all rows in the grid. It's important to note that this ...

A guide to organizing elements in Javascript to calculate the Cartesian product in Javascript

I encountered a situation where I have an object structured like this: [ {attributeGroupId:2, attributeId: 11, name: 'Diamond'}, {attributeGroupId:1, attributeId: 9, name: '916'}, {attributeGroupId:1, attributeId: 1, name ...

Utilize React to generate HTML content and send it as the email body through Node.js

I am currently working on a react application that consists of two main pages - AddStatus and ViewStatus. Both of these are implemented as react components. My current task involves sending out an email daily at a specific time, containing the details dis ...

JavaScript - Deserializing an array of strings

I am facing an issue with converting a string to an array. The original string looks like this: a= "['url1','url2','url3']" When trying to convert it to an array, it should look like this: arr = ["url1","url2","url3"] Howe ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

Tips for effectively managing 404 errors in Angular 10 with modular routing

I'm facing challenges with handling 404 pages within an Angular 10 application that utilizes modular routing architecture. Here is the structure of my code: |> app |-- app.module.ts |-- app-routing.module.ts |-- app.component{ts, spec.ts, scss, ht ...

How can I showcase the data from a JSON file on a website using Jquery.GetJSON in combination with HTML/JS on a

I have searched for similar questions, but none of the answers have solved my issue. The JSON code can be found at this link. I am attempting to show the "value_sell" and "value_buy" objects from the "official" and "blue" sections. I have inserted the fo ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

Using JQuery, ensure that the scroll function runs in advance of the ajax call finishing

I am currently working on using jQuery to scroll down to a text box when the click event occurs. However, I have noticed that the scroll event is happening after the AJAX call within the function. $("#execute_btn").click(function(){ $('html, b ...

Managing multiple photo uploads using React JS and Laravel

I am trying to use axios in ReactJS to upload multiple images to the database, send the data from client-side to server-side, and handle image uploads with Laravel on the backend. However, I am encountering an issue when attempting to process multiple imag ...

javascript while loop not functioning properly

Can someone assist me with troubleshooting this while loop issue? <script type="text/javascript"> var num = window.prompt("Please enter a score"); var sum, average; var count=0; while (num > 0) { sum += num; ...

When attempting to update a task with the Microsoft Graph API, the server returned a 400 error code

Attempting to update a Task using the Graph API from an angular2 typescript app. Here is an example of my request - Request URL:https://graph.microsoft.com/beta/tasks/_1EKXXuN1UGInJ9yVHAjIpYAKuC2 Request Method:PATCH Request Body: { "createdBy":"f16 ...

Displaying consistent headers on all printed pages in Chrome browser using Vue.js

Hey there, I'm currently working on code to print the page in my Vue web application. I want to have a static header appear on every page, either by using CSS or JavaScript. I've created a header div component and set its position as fixed. It&ap ...

Disabling the scrollbar in Selenium screenshots

When using Chromedriver to capture screenshots of webpages, my code effectively does the job. However, I am now facing an issue with removing the unsightly scrollbars from the image. Is it feasible to inject CSS into the webpage in order to achieve this? W ...

Accessing a property in Typescript is limited to a specific union type

I am relatively new to Typescript, so please bear with me as I navigate through this challenge. In a specific use-case scenario I have created an array that can contain instances of both "Class One" and "Class Two". My goal is to iterate through this arra ...

Ensure to install jpm globally using the following command: npm install

Experiencing issues with nodejs after running the command npm install jpm --global. Any insights into what may be causing this error? npm-debug.log Encountering an error message after executing the command. The log shows a failure to replace env in the ...

Getting the value of a lookup in an alert or console within a Material table in React

I am currently integrating a material table into my project and I have encountered an issue. Instead of getting the name of a city, I am receiving numbers like 63 or 32 in alerts or console logs. For reference, here is the link to the CodeSandbox: https:/ ...