Skip to content

Instantly share code, notes, and snippets.

@aminsaedi
Last active January 11, 2023 03:35
Show Gist options
  • Save aminsaedi/6e034a41b75b8f7d7e21e618d91319b8 to your computer and use it in GitHub Desktop.
Save aminsaedi/6e034a41b75b8f7d7e21e618d91319b8 to your computer and use it in GitHub Desktop.
Ant design v5 time picker with time zone

I created two custom components to fix the the issue with ant design time picker component using dayjs.

Just make sure that you load the utc and timezone plugin of dayjs and also call the dayjs.tz.setDefault("YOUR_TIMEZONE") somewhere in your code

import React, { useMemo } from 'react'
import dayjs from 'dayjs'
import { DatePicker, DatePickerProps } from 'antd'
import useToken from 'hooks/useToken'
import useCurrentProfile from 'hooks/useCurrentProfile'
type Props = {
value?: string
onChange?: (i: string | null) => void
disableTimezone?: boolean
showTime?: boolean
} & Omit<DatePickerProps, 'value' | 'onChange'>
const dateFormat = 'YYYY-MM-DD'
export default function AppDateTimePicker({
value,
onChange,
disableTimezone,
showTime = true,
}: Props) {
const { timeZone } = useToken()
const { preferredDateTimeFormat, preferredDateFormat } = useCurrentProfile()
const pickerValue: dayjs.Dayjs | null = useMemo(() => {
return value ? (disableTimezone ? dayjs(value) : dayjs(value).tz(timeZone)) : null
}, [value, disableTimezone, timeZone])
const handleChange = (i) => {
if (!onChange) return
if (i) {
if (showTime)
if (disableTimezone) {
onChange(i.format())
} else onChange(i.tz(timeZone, true).utc().format())
else {
if (disableTimezone) {
onChange(i.format(dateFormat))
} else onChange(i.tz(timeZone, true).utc().format(dateFormat))
}
} else onChange(null)
}
return (
<DatePicker
showTime={showTime}
format={showTime ? preferredDateTimeFormat : preferredDateFormat}
className="w-100"
value={pickerValue}
onChange={handleChange}
/>
)
}
import React from 'react'
import dayjs from 'dayjs'
import { TimePicker, TimePickerProps } from 'antd'
import useToken from 'hooks/useToken'
type Props = {
value: string
onChange: (i: string | null) => void
disableTimezone?: boolean
} & TimePickerProps
export default function AppTimePicker({ value, onChange, disableTimezone, ...rest }: Props) {
const { timeZone } = useToken()
return (
<TimePicker
className="w-100"
format="HH:mm"
{...rest}
value={
value
? disableTimezone
? dayjs(value, 'HH:mm:ss.SSSZ')
: dayjs(value, 'HH:mm:ss.SSSZ').tz(timeZone)
: null
}
onChange={(i) => {
if (i) {
if (disableTimezone) {
onChange(i.format('HH:mm:ss.SSSZ'))
} else onChange(i.tz(timeZone, true).utc().format('HH:mm:ss.SSSZ'))
}
return null
}}
/>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment