I am using moment-timezone in a React project and after installing moment-timezone with
yarn add moment-timezone
my project had this entry in the package.json library. After testing locally the moment-timezone separately in a js file which I ran with node everything seemed to be ready to go ahead and start using the library in React.
This is by the way my experimentation script in which I create a moment object with Los Angeles time and convert it to other time zones:
var moment = require('moment-timezone');
const timeLA = moment().tz("Europe/London").format();
console.log(timeLA);
const sampleMoment = moment('2020-07-06T10:00');
console.log(sampleMoment.tz("Europe/London").format());
console.log(sampleMoment.tz("Europe/Vienna").format());
const sampleMoment2 = moment.tz('2020-07-06 10:00', "America/Los_Angeles");
console.log('2020-07-06T10:00', "where you are", sampleMoment2.tz(moment.tz.guess()).format());
console.log('2020-07-06T10:00', "London", sampleMoment2.tz("Europe/London").format());
console.log('2020-07-06T10:00', "Lisbon", sampleMoment2.tz("Europe/Lisbon").format());
So I went to import moment-timezone in my project with:
import moment from "moment-timezone";
and wrote a factory function using this library:
function momentFactory(dateExpr, timezone) {
return timezone ? moment.tz(dateExpr, timezone) : moment(dateExpr);
}
After my React page restart I started seeing these errors (more than 100):
Moment Timezone has no data for America/New_York. See http://momentjs.com/timezone/docs/#/data-loading/.
This is quite weird because in my previous experiment just by importing the library I would have data for all possible time zones. I have no clue why something that works well in a pure node environment will not work the same way on the browser.
As a workaround I ended up by loading in my function the timezone data, but I guess this is a kind of a hack:
function momentFactory(dateExpr, timezone) {
moment.tz.load(require('moment-timezone/data/packed/latest.json'));
return timezone ? moment.tz(dateExpr, timezone) : moment(dateExpr);
}
Is there a way to load the library properly without this workaround in a project which was bootstrapped by create-react-app?
Change your import statement to:
import moment from 'moment-timezone/builds/moment-timezone-with-data';
Or if you prefer the truncated smaller data set:
import moment from 'moment-timezone/builds/moment-timezone-with-data-10-year-range';
(You can use any of the data files from the builds directory.)
Also, if you are creating a new application, and targeting modern web browsers, please consider using Luxon instead of Moment. Luxon is in the Moment family, but provides an immutable API, modern packaging features, and uses the built-in time zone data from modern browsers rather than requiring you to distribute time zone data with your application. Please use Moment only if you are already using it in a legacy application, or if you require support for older web browsers. Thanks.