0

peeps of stackoverflow, so I'm working on this event for my site. I'm really close on figuring it out but I am stuck on an issue. The issue is, I get a NaN returned when I'm trying to display how many days it has been since the last I updated a tab. Just side note, I'm manually updating the date via ID tag and JavaScript is doing the rest. Here is my HTML part of the event :

<span onload="manualDate('07-27-2021');" id="demoDate"></span> 

Here is JS calculation for getting MS per day

const _MS_PER_DAY = 1000 * 60 * 60 * 24 * 30;

This part is stringing the date and modifying the numbers if they are single digits

var today = new Date();
var dd = today.getDate();

var mm = today.getMonth()+1; 
var yyyy = today.getFullYear();
if(dd<10) 
{
    dd='0'+dd;
} 

if(mm<10) 
{
    mm='0'+mm;
} 

Here, I am fetching the id value in the HTML span area and using that value and setting it

today = mm+'-'+dd+'-'+yyyy;
var newSetdate;

function manualDate(a) {
    newSetdate = '"' + a + '"';
    return newSetdate;
}

And lastly , This is the function that ties everything together. For some reason, the diffrence valued is NaN and im not sure why.

function dateDiffInDays(a, b) {
    const utc1 = Date.UTC(a.getMonth(), a.getDate(), a.getFullYear());
    const utc2 = Date.UTC(b.getMonth(), b.getDate(), b.getFullYear());

    return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}

const   a = new Date('"' + newSetdate +'"'),
        b = new Date('"' + today +'"'),
        difference = dateDiffInDays(a, b);
        
document.getElementById("demoDate").innerHTML = difference + " days ago";
James
  • 21
  • 7
  • 1
    I'd suggest you use a date library like [Luxon](https://moment.github.io/luxon/#/) – Liam Jul 29 '21 at 12:33
  • 1
    Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. If you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Jul 29 '21 at 12:34
  • 3
    You need to check the documentation for [`Date.UTC`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC) -- you're giving it its arguments in the wrong order. – T.J. Crowder Jul 29 '21 at 12:34
  • In Safari at least, `new Date('07-27-2021')` returns an invalid Date, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Jul 29 '21 at 12:47
  • Given the *diffDate* function takes Dates with the hours set to zero as arguments, it can be simplified to `Math.round((a - b) / 8.64e7)`. – RobG Jul 29 '21 at 12:53

1 Answers1

1

I'd suggest the following changes:

  1. Store the tab's date as a data-* attribute
  2. Format the date so it's parsable by the built–in parser, i.e. use a format supported by ECMA-262 such as yyyy-mm-dd
  3. Simplify the calculation of days by doing everything as UTC so days are always exactly 8.64e7 ms long — serendipitously yyyy-mm-dd is parsed as UTC so that's accounted for by #2 above ;-)

Presumably you just want to count whole days and not worry about the time, so:

function updateDate(el) {
  // Dates in the format yyyy-mm-dd are parsed as UTC
  let lastUpdateDate = new Date(el.dataset.lastUpdate);
  // Get difference from current date as UTC
  let now = new Date();
  let diffDays = (Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()) - lastUpdateDate) / 8.64e7;
  // Write output to element, allowing for day/s
  el.textContent = `The last update was ${diffDays} day${diffDays == 1? '' : 's'} ago`;  
}

window.onload = () => document.querySelectorAll('.demoDate').forEach(el => updateDate(el));
<p>2021-07-30: <span data-last-update="2021-07-30" class="demoDate"></span>
<p>2021-07-31: <span data-last-update="2021-07-31" class="demoDate"></span>
<p>2021-08-01: <span data-last-update="2021-08-01" class="demoDate"></span>
RobG
  • 142,382
  • 31
  • 172
  • 209
  • Thank you @RobG . And those who else answered my question. You guys really helped – James Jul 31 '21 at 21:50
  • @James—I corrected the use of UTC methods, they should have been local. You would only have noticed the error if run within the local offset of midnight. – RobG Aug 01 '21 at 02:32