简体   繁体   English

时区独立日期 javascript

[英]Timezone independent dates javascript

Using javascript/react native + redux i need to save timestamps in a time format that is aware of local time when saving the date, but unaware when reading the same date in another timezone.使用 javascript/react native + redux 我需要以一种时间格式保存时间戳,该格式在保存日期时知道本地时间,但在另一个时区读取相同日期时不知道。

Take a hypothetical user that travels west around the world in one day, saving a time stamp every hour, all i different timezones, all at 2021-01-30 at 18:00 hours local time.假设一位用户在一天内向西环游世界,每小时保存一个时间戳,所有不同的时区,时间均为当地时间 2021 年 1 月 30 日 18:00。 Resulting in 24 timestamps at 18:00.在 18:00 产生 24 个时间戳。

Using a function in the likes of isWithinInterval from date-fns in a similar fashion as below, all timestamps should return true.date- fns 中的isWithinInterval中使用 function 以类似于下面的方式,所有时间戳都应该返回 true。

isWithinInterval(
  timestamp,
  {start: new Date(2021,0,30,17,30}, end: new Date(2021,0,30,18,30)}, 
) // -> true

How do one go about doing this?一个 go 如何做到这一点? Preferrably in a react-redux compatiable (serializable) way.最好采用 react-redux 兼容(可序列化)方式。 By default, your date object will be saved in UTC based on the local time on your device.默认情况下,您的日期 object 将根据您设备上的本地时间以 UTC 格式保存。

I had such a hard time to wrap my head around the date objects that it took a long time for me to understand that this problem is actually what "date-fns-tz" package is all about.我很难理解日期对象,以至于我花了很长时间才明白这个问题实际上是“date-fns-tz”package 的全部内容。 This is how i'm currently solving it:这就是我目前解决它的方式:

  1. Create a utc-time identical to the local time using:使用以下命令创建与本地时间相同的 UTC 时间:
import {zonedTimeToUtc} from "date-fns-tz"
const myDate = new Date()  // eg 2021-02-03 10:00 UTC +5
const localTimeIdenticalUtc = zonedTimeToUtc(localDateObject, localTimeZone)  // 2021-02-03 10:00 UTC +-0
  1. When i want to use the UTC-date, i transfer it back to an identical localDate for whatever time zone i am in.当我想使用 UTC 日期时,无论我在哪个时区,我都会将它转移回相同的 localDate。
    import {utcToZonedTime } from "date-fns-tz"
    const zonedTimeToUtc(localTimeIdenticalUtc, localTimeZone) // 2021-02-03 10:00 UTC +5

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

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