I am using MomentJS in my angular project and i'm having a lot of issues with different date timezones.
My app should not take into consideration any timezones, however this chaos between my backend api and frontend, when i send standard moment objects to c# backend it converts it to UTC by default and i always get the dates -1 day.
Can i set MomentJS or javascript Date object to always default to UTC AND ignore hour/minutes/seconds ?
When i do: moment()
it gets populated with today value based on timezone and based on current hour.
I want to make moment()
always have UTC value and time always be 00:00:00 in my entire app.
Is it also possible to achieve this also with new Date()
?
Right now i've been always using .toUTCString()
after new Date()
but i have a ton of date variables in my solution and it's not really ok to make sure everything has .toUTCString()
after it all the time, if another dev misses this it will cause issue. I'm trying to find a way to standardize this at project level.
My major issue is with momentJS compare methods .isBefore()
, .isSame()
, .isAfter()
. Because all my dates contain different hours and different time zone when the compare happens it will take them into account and not behave how i want them to.
You can use moment-timezone with moment
.
And then set default UTC
timezone with code below:
import * as moment from 'moment-timezone';
...
moment.tz.setDefault('Etc/UTC');
A possible option in Angular could be to create a singleton instance LocaleService
to manage localization related parameters.
import { Injectable } from '@angular/core';
import * as moment from 'moment-timezone';
@Injectable({
providedIn: 'root'
})
export class LocaleService {
constructor() {
this.setDefaultTimezone();
}
setDefaultTimezone() {
moment.tz.setDefault('Etc/UTC');
}
// other stuff related to localization
...setCurrentTimezone()
...setLocale()
}
And then, we need to provide this service via AppModule
, and also don't forget to inject it in a global component, for instance AppComponent
, in order to be instantiated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With