0

I have added today: number = Date.now(); in my angular code . but it gets the time after adding 5 hours to my local time. Not sure what is wrong.

today: number = Date.now();

My HTML code that displays time on screen

<p class="date-format-layout-vertical-align">
    Printed &nbsp; &nbsp; {{ today | date: 'short' }}
</p>
commadelimited
  • 5,656
  • 6
  • 41
  • 77
Ryan
  • 39
  • 1
  • 10
  • what do you mean by `it gets the time after adding 5 hours to my local time` – Aravind Oct 02 '19 at 16:19
  • Have you verified that the value of `today` is the local time, and not the local time plus five hours? – Alexander Nied Oct 02 '19 at 16:20
  • My local time is 11.10AM . It displays 4:10PM on my main report – Ryan Oct 02 '19 at 16:21
  • What happens when you use new Date() instead of Date.now? – MikeOne Oct 02 '19 at 16:45
  • @MikeOne - gets me the same time. No change – Ryan Oct 02 '19 at 18:29
  • Right. So are you setting a locale in your Angular app somewhere? – MikeOne Oct 02 '19 at 18:31
  • @MikeOne am not sure what that exactly is - but I have something `public locale: string = 'en-us';` in my code – Ryan Oct 02 '19 at 18:35
  • @MikeOne What can I do to check whether if a locale is getting set or not. If NOT, how can I set one? – Ryan Oct 02 '19 at 18:45
  • You could try to use https://angular.io/api/common/formatDate.. however, unless there is something weird going on with your setup (wrong timezone on your local machine, or some provider that forces a locale) - this should really not be needed to get it right.. – MikeOne Oct 02 '19 at 18:49
  • @MikeOne is there a way I can somehow stick in my function in the HTML itself so that it gets the browser time automatically. ? – Ryan Oct 02 '19 at 19:21
  • @MikeOne It's still getting the the UTC time for me. not sure what needed to be changed to get this working. Can you suggest something ? – Ryan Oct 02 '19 at 20:36
  • Maybe there are some clues here: https://stackoverflow.com/questions/53874731/angular-6-typescript-new-date-is-created-in-utc-but-i-need-in-my-local-timezone – MikeOne Oct 02 '19 at 20:42

1 Answers1

0

Use new Date() instead of Date.new().

When no parameters are provided, the newly-created Date object represents the current date and time, specified in the local time zone, as of the time of instantiation.
Further reading

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
Further reading

Edit

You can also try to subtract the time offset and then use the pipe {{ getDate() | date: 'short }}

public getDate(): string {
    const date = new Date()
    date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
    return date.toISOString()
}
Norbert Bartko
  • 2,468
  • 1
  • 17
  • 36