Want to set timezone React-Datepicker? Use the following react code to set timezone React-Datepicker.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import React, { ComponentProps } from "react" import DatePicker from "react-datepicker" import moment from "moment" interface Props { timezone: string } const DatePickerWithTimezone = ({ selected, onChange, timezone, ...props }: Props & ComponentProps<typeof DatePicker>) => ( <DatePicker selected={selected ? setLocalZone(selected, timezone) : null} onChange={(v, e) => { onChange(v ? setOtherZone(v, timezone) : null, e) }} {...props} /> ) const setLocalZone = (date: Date, timezone: string) => { const dateWithoutZone = moment .tz(date, timezone) .format("YYYY-MM-DDTHH:mm:ss.SSS") const localZone = moment(dateWithoutZone).format("Z") const dateWithLocalZone = [dateWithoutZone, localZone].join("") return new Date(dateWithLocalZone) } const setOtherZone = (date: Date, timezone: string) => { const dateWithoutZone = moment(date).format("YYYY-MM-DDTHH:mm:ss.SSS") const otherZone = moment.tz(date, timezone).format("Z") const dateWithOtherZone = [dateWithoutZone, otherZone].join("") return new Date(dateWithOtherZone) } export default DatePickerWithTimezone |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.