'moment.calendar shows today as the day instead of 5 days ago

I am using moment version 2.24.0 (I did have an older version but updated to see if it fixed this problem, which it didn't), in Angular application.

I have the following code

import * as moment from 'moment';
import 'moment-duration-format';
....
    
public static formatTime(dateTime: Date): string {  
        // To test am subtracting 5 days from today..
        dateTime.setDate(dateTime.getDate() - 5);

        // dateTime now show Tuesday, which is correct
        let result = moment().calendar(dateTime);

        // Result show Sunday! (wrong)
        return result;
      }

I am subtracting 5 days just to test the calendar() formatting.

From the debugger:

enter image description here

As can be seen, the calendar() is displaying Sunday (which is today), but it should be Tuesday. Are there any workarounds for this?

Update 1

Added a Plunker example of this here.

See script.js for the code.



Solution 1:[1]

if you give 5 to setDate function:

dateTime.setDate(dateTime.getDate() - 5);

you get the correct time - 5 Milliseconds.

to get X days ago you need to give:

let today  = new Date()
5DaysAgo = new Date(today .getTime() - (5 * 24 * 60 * 60 * 1000)); 

Solution 2:[2]

Since you are using moment, why don't you just use it? In particular, instead of manipulating the Date, subtract 5 days using moment...

console.log(moment(new Date()).subtract(5, 'days').calendar());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>

Solution 3:[3]

Try

 let result = moment().calendar(dateTime.getDate());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 dileepkumar jami