My application requires material-ui date and time pickers to function based on a remote time zone specified by the server. I want the today circle on the date picker to accurately reflect today in the remote time zone, and I need to convert the datetimes in that time zone to seconds since 1970-01-01T00:00:00Z
.
I am currently using the material-ui v5 alphas. According to the documentation, you need to specify a @date-io
adapter for your time library. There are four options available:
@date-io/date-fns
(based on date-fns and date-fns-tz) has issues with handling remote time zones due to its usage of Javascript Dates. As a result, there are limitations during daylight saving time transitions. Read more about this here.@date-io/dayjs
(based on dayjs) does not handle daylight saving time correctly. For further information, check this issue@date-io/luxon
(based on luxon) seems promising.@date-io/moment
(uses moment and moment-timezone) also appears promising.
Hence, I aim to select an adapter for either luxon or moment that constructs dates within a specific time zone.
While both libraries support setting a global default time zone (luxon, moment), I prefer setting a time zone when creating a particular date adapter rather than modifying global state based on the server response.
A discussion related to @date-io mentions:
You can pass moment-time zone directly to the
libInstance
which will then utilize the time zone set on the moment instance or the global one.
This is exactly what I need! However, as someone relatively new to JavaScript, I find it confusing to grasp the concept of this 'instance'.
Currently, the constructor for @date-io/luxon
doesn't seem to allow overriding the instance.
Attempting to make the moment option work, the following steps were taken:
$ mkdir tztest
$ cd tztest
$ npm init -y
$ npm install --save moment moment-timezone '@date-io/moment'
$ node
> let MomentUtils = require('@date-io/moment');
undefined
> let moment = require('moment');
undefined
> let _ = require('moment-timezone');
undefined
> // Various operations should ideally work similarly to utilizing the default instance:
> (new MomentUtils()).date();
Moment<2021-03-18T11:57:30-07:00>
...
(Javascript interpreter outputs here)
...
After reviewing the source code from @date-io/moment
, multiple applications of the library are observed. It is crucial that all these functionalities operate smoothly in my project.
export default class MomentUtils implements IUtils<defaultMoment.Moment> {
...
constructor({ locale, formats, instance }: Opts = {}) {
this.moment = instance || defaultMoment;
...
return /A|a/.test(this.moment().localeData().longDateFormat("LT"));
...
return this.moment.localeData().longDateFormat(token as LongDateFormatKey);
...
return this.locale || this.moment.locale();
...
return this.moment(value, format, this.locale, true);
...
return this.moment(value, format, true);
...
const moment = this.moment(value);
...
return this.moment.weekdaysShort(true);