我使用react-datepicker让用户选择日期。但是,现在它使用本地时间(PDT),但我希望将其硬编码为使用特定的时区(PST)。
我试过使用utcOffset prop,但它似乎没有任何作用。有谁知道如何做到这一点吗?
发布于 2019-10-23 17:42:38
对于我来说,我在呈现React-dates插件之前设置了defaultTimezone。React-date将只使用默认时区。
moment.tz.setDefault('America/Los_Angeles');发布于 2020-01-22 18:49:32
这对我来说很有效:
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发布于 2020-04-11 21:16:26
由于datepicker不再使用moment.js,因此我尝试实现了一个解决此问题的解决方案,假设初始值是一个字符串:
export const formatUTC = (dateInt, addOffset = false) => {
let date = (!dateInt || dateInt.length < 1) ? new Date : new Date(dateInt);
if (typeof dateInt === "string") {
return date;
} else {
const offset = addOffset ? date.getTimezoneOffset() : -(date.getTimezoneOffset());
const offsetDate = new Date();
offsetDate.setTime(date.getTime() + offset * 60000)
return offsetDate;
}
}在date内部,我像这样调用格式化程序:
selected={formatUTC(this.props.input.value,true)}
onChange={date => formatUTC(date)}https://stackoverflow.com/questions/53052012
复制相似问题