Utilizing material-ui's LocalizationProvider to display times in a different time zone

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);

Answer №1

There is a discrepancy in material-ui documentation and date adapter integration API across different major versions.

I successfully implemented moment-timezone with

@material-ui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2858414b434d5a5b681c06180618054944584049061919">[email protected]</a>

dependencies

"@material-ui/core": "4.11.3",
"@material-ui/pickers": "4.0.0-alpha.11",
"moment": "2.29.1",
"moment-timezone": "0.5.33",
"react": "17.0.2",
"react-dom": "17.0.2"

working demo

https://codesandbox.io/s/material-ui-starter-template-forked-pvpmc

code example

import React from "react";
import { render } from "react-dom";
import momentTimezone from "moment-timezone";
import { TextField } from "@material-ui/core";
import { DatePicker, LocalizationProvider } from "@material-ui/pickers";
import MomentAdapter from "@material-ui/pickers/adapter/moment";

const App = () => {
  const timeZoneFromServer = "Asia/Tokyo";
  const { moment } = new MomentAdapter({ instance: momentTimezone });
  const dateWithTimeZone = moment().tz(timeZoneFromServer);

  const handleDateChange = () => {};

  return (
    <LocalizationProvider dateAdapter={MomentAdapter}>
      <DatePicker
        renderInput={(props) => <TextField {...props} />}
        value={dateWithTimeZone}
        onChange={handleDateChange}
      />
    </LocalizationProvider>
  );
};

render(<App />, document.getElementById("root"));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing AngularJS: Techniques for Binding Data from Dynamic URLs

Just starting out with AngularJS We are using REST APIs to access our data /shop/2/mum This URL returns JSON which can be bound like so: function ec2controller($scope, $http){ $http.get("/shop/2/mum") .success(function(data){ ...

All You Need to Know About Jquery's Selector for Nested Elements

Could someone clarify if the Jquery Statement $(selecterA:not(selectorB), elementA) means "return those elements that match selectorA but not selectorB within elementA"? I am confused by a simple case in Fiddle#1, where both output statements using .length ...

What is the best way to retrieve the current value of a React useState hook within a setInterval function while using Highcharts

import Error from 'next/error' import React, { useState, useEffect } from 'react' import Highcharts from 'highcharts' import HighchartsReact from 'highcharts-react-official' function generateChart() { const [co ...

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

Develop a library of components using TypeScript and Less files

I'm currently in the process of creating a React UI library that will consist of various components such as Buttons, Inputs, textareas, etc. This library, which I've temporarily named mylib, will be reused across multiple projects including one c ...

Encountered an unexpected interpolation ({{}}) in column 3 of Data Bind RouterLink (Angular 2) that was expecting an expression

Encountering difficulties passing data to my routerLink. The goal is to change the route when the id reaches 4 within the ngFor loop. <input type="button" class="btn-cards" [ngClass]="getStyle(negociacao)" [routerLink]="['/{{negociacao.rota}}&apo ...

How can I create and assign types dynamically in TypeScript?

I'm working on creating an SX styling file with a style object of type SXPropsTypes. In another file, I'm having trouble accessing the style properties because the autocomplete isn't suggesting the keys of my style object. style.ts import { ...

Determining the file path in HTML5

Can anyone help me with retrieving the file path using html5 javascript once a user selects a file? I require the file path for a specific scenario: In this case, the user uploads a file and pauses it (currently only supported by Mozilla browsers), then c ...

javascript / php - modify input fields according to selection change

Can anyone help me with an issue I'm facing? I want to update multiple textfields whenever a new option is selected from my dropdown menu. I've written the following code, but it's not working as expected. Can someone figure out what's ...

Tips for creating a multitude of components

I have my react code in a single component and I am wondering how to split it into two components for the images container and showroom images. import React, { Component } from 'react'; export default class App extends Component { render() { ...

Insert a new row into the table using jQuery right above the button

I am working on a table where I need to dynamically add rows in the same rowId upon clicking a specific button. For instance, when the "Add Row 1" button is clicked, a new row should be added under "Some content 1", and so on for other rows. <table i ...

Looking for a JavaScript regex pattern that matches strings starting with the letter "p" and containing at least

I have recently started learning about JavaScript regular expressions. I attempted the following expression for a string starting with the letter "p" followed by digits: p1749350502 The letter "p" is constant and the remaining digits are variable. Howeve ...

At what point are functions executed? What methods can I use to manage their execution?

Looking to make a simple call to an API using jQuery's $.get() function as a JS beginner. The issue I'm facing is that the function seems to be called randomly rather than where I expect it in my code. I am open to either doing everything inside ...

Why is it that a JSX element can take a method with parentheses or without as its child?

Why is it that when I attempt to pass a method without parentheses into a React component as a child of one of the JSX elements, an error appears in the console? However, simply adding parentheses resolves the issue. What's the deal? For example: ran ...

Looking to dynamically track an event in Firestore?

Is it possible to implement a method in Node.js that allows me to listen for changes on a node, similar to the following path? organizations/{org_slug}/projects/{pro_slug}/calculations/{calc_slug} I have successfully done this in a Firebase Cloud Functio ...

What is the URL I need to visit in my browser to monitor updates while running npm?

I am interested in utilizing npm to monitor any changes made in my project and immediately view them in my browser. Essentially, I have been implementing npm using this modified code snippet from this source, which allows me to run the command npm run buil ...

Using the event object in the onClick handler within React applications

In my React app, I have implemented a feature where clicking on a column heading sorts the data in the table using merge sort algorithm My goal is to pass both the data (an array of objects) and the event object to the sorting function. However, I am faci ...

Observing nested data changes in Vue.JS?

In my Vue.js components, I have a group of checkboxes that are sending data to the parent element. My goal is to monitor this data for changes and use it to filter information in an API call. When certain checkboxes are selected, the data stored on the pa ...

Is a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

Triggering a dynamically created event with the onchange event

I'm currently working on creating an input type file, and here is the code I have: var element = document.createElement("INPUT"); element.type = "file"; element.id = "element" + i; $("#media").append("<br>"); $("#media").append("<br>"); $ ...