简体   繁体   English

React Native:我正在使用社区的日期时间选择器,它将我的时间转换为 GMT+0

[英]React Native: I am using date time picker from community and it is converting my time to GMT+0

I am on GMT+3 and when I use @react-native-community/datetimepicker.我在 GMT+3 时使用 @react-native-community/datetimepicker。 It converts my date automatically to the GMT+0.它会自动将我的日期转换为 GMT+0。 You can check my code below.您可以在下面查看我的代码。 Do someone now why it is converting?现在有人为什么要转换? Thank you!谢谢!

DATE TIME PICKER日期时间选择器

 <DateTimePicker
   testID="dateTimePicker"
   value={data[name]} // value={new Date()}
   mode={type} // mode="time"
   is24Hour={true}
   display="spinner"
   onChange={handleChange}
   minimumDate={type === "date" ? new Date() : undefined}
 />

HANDLE CHANGE FUNCTION手柄变更功能

const handleChange = (event: any, selectedDate: Date) => {
setShow(false)

console.log(selectedDate) // returns the selected date - 3 hours

if (selectedDate) {
  setDate(formatDate(selectedDate, type))
  setData({ ...data, [name]: selectedDate })
}

} }

I fixed it.我修好了它。 I converted the time to the user device timezone by using a function before setDate.我使用 setDate 之前的函数将时间转换为用户设备时区。

UPDATE for the if from handleChange:更新来自 handleChange 的 if:

  setByTimezone(selectedDate)      
  setDate(formatDate(selectedDate, type))    
  setData({ ...data, [name]: selectedDate })

FUNCTION setByTimezone(this is the code for typescript, if someone with javascript want to use it, remove the types): FUNCTION setByTimezone(这是打字稿的代码,如果有javascript的人想使用它,请删除类型):

const setByTimezone = (time: Date): void => {
  const date: Date = new Date()
  const difference: number = -date.getTimezoneOffset() / 60

  time.setHours(time.getHours() + difference)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM