0

I am very new to Angular. Presently I am using Angular5. Could someone guide me how to get the datetime for a given timestamp for n hours ago, n days ago?

Like I want to know the datetime 7 hours ago / 30 days ago etc for NY timezone,.

Many Thanks, Thillai

3 Answers3

1

I would consider using moment.js which allows you to do calculations like:

moment().subtract(10, 'days').calendar(); // 04/20/2020
moment().subtract(6, 'days').calendar();  // Last Friday at 2:17 PM
moment().subtract(3, 'days').calendar();  // Last Monday at 2:17 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 2:17 PM
moment().calendar();                      // Today at 2:17 PM
moment().add(1, 'days').calendar();       // Tomorrow at 2:17 PM
moment().add(3, 'days').calendar();       // Sunday at 2:17 PM
moment().add(10, 'days').calendar();  

You can also use moment timezone: https://momentjs.com/timezone/

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00
John McArthur
  • 916
  • 1
  • 12
  • 30
1

You should consider using a library like moment.js, and an excellent answer is here

Kisinga
  • 1,640
  • 18
  • 27
  • 2
    Just as a piece of advice, if you use Angular, consider using date-fns instead of moment.js. Date-fns is tree-shackable, moment isn’t.. – MikeOne Apr 30 '20 at 13:43
  • 1
    Appreciate the suggestion, maybe you can suggest an aswer applicable to this question before I withdraw mine – Kisinga Apr 30 '20 at 19:36
0

You don't need angular, you just need to manage it with Javascript inside Angular.

let dte = new Date();
dte.setDate(dte.getDate() - 30);
this.daysAgo = dte.toString();

Or, for hours:

this.hoursAgo = new Date(new Date().getTime() - (7 * 60 * 60 * 1000));

JS Snippet

Sandman
  • 1,480
  • 7
  • 23