Date difference calculation in C# vs Moment.js

Viewed 432

I was doing calculation on two dates. I need to find how much days left for the user to use their contract in the site. I have expiry date stored in the DB. And I need to compare this with the current date and get the remaining days left to enjoy their subscription.

Initially this number of days remaining calculation was in the C#.

var daysLeft = Convert.ToInt32((data.expiryDate.Date - DateTime.Now.Date).TotalDays);
//Say, the expiryDate is Thu Dec 31 2020 00:00:00 GMT+0530 (India Standard Time), And daysLeft is 220 for the above statement

And Now i tried the same in Moment.js in client side.

moment(data.expiryDate).diff(moment(), 'days')
//Say, the expiryDate is Thu Dec 31 2020 00:00:00 GMT+0530 (India Standard Time) and it is giving 219.

I also tried like subtracting two dates in same format after converting it to YYYY-DD-MM as below which is giving the error

moment(data.expiryDate).format('YYYY-DD-MM').diff(moment().format('YYYY-DD-MM'), 'days')
Object doesn't support property or method 'diff'

Why in C# its 220 and in moment.js it is 219? Am I missing anything? Please suggest me where the calculation goes wrong.

2 Answers

When you do this in c#:

data.expiryDate.Date - DateTime.Now.Date

you actually substract whole days (because .Date results in time being 00:00:00.000).

Now, you do the Following in js:

moment(data.expiryDate).diff(moment(), 'days')

and the difference here is that you substract date & time.


Note (use of .Now without .Date):

var expiryDate = DateTime.Parse("12/31/2020 10:00:00");
Console.WriteLine((expiryDate.Date - DateTime.Now).TotalDays);

returns 219.654703995023 when the same code with .Date returns 220


TL;DR:

---------------------------------------------------------------
|       moment.js       |       C#                            |
---------------------------------------------------------------
|moment()               | DateTime.Now                        |
|moment().startOf('day')| DateTime.Today (=DateTime.Now.Date) |
---------------------------------------------------------------

If you want the same result for your javascript part, you should probably use .startOf('day') (which seems to be the equivalent of .Date according to Moment.js | Home)

In C#, TotalDays represents whole and fractional days, the return type is double. And convert to int will round to the nearest 32-bit signed integer. In moment.js, diff will truncate the result to zero decimal places, returning an integer. But before 2.0.0, diff returned a number rounded to the nearest integer, not a truncated number.

Related