[英]Javascript find time difference in hours with timezone
I have a javascript object with the following details:我有一个 javascript object 具有以下详细信息:
var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date = date.toLocaleString('en-US', options) console.log(curr_date) //I want this //diff = curr_date - dateobj.date
I want to find the time difference in hours with the current date-time of the same timezone.我想用同一时区的当前日期时间找到以小时为单位的时差。 I know I can use
toLocaleString()
function to get the date-time string in a particular timezone, but how can I find the time difference?我知道我可以使用
toLocaleString()
function 来获取特定时区的日期时间字符串,但是如何找到时差? The above code gets the current date time in that timezone, how can I find the time difference in hours?上面的代码获取该时区的当前日期时间,我怎样才能找到以小时为单位的时差?
In general when working with dates in JS I usually use a library called date-fns
(Date functions).一般来说,在 JS 中处理日期时,我通常使用一个名为
date-fns
(日期函数)的库。 It just makes dates and time a lot easier to manage.它只是使日期和时间更容易管理。 This is how you would get the time difference in hours with
date-fns
.这就是您如何使用
date-fns
获得以小时为单位的时差。
const { differenceInHours } = require("date-fns");
const { zonedTimeToUtc } = require("date-fns-tz");
const timeData1 = {date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3};
const timeData2 = {date: "2020-12-21 03:31:06.000000", timezone: "America/Los_Angeles", timezone_type: 3};
const t1 = zonedTimeToUtc(timeData1.date, timeData1.timezone);
const t2 = zonedTimeToUtc(timeData2.date, timeData2.timezone);
const diff = differenceInHours(t2, t1);
console.log(diff);
// => 8
Run demo: https://runkit.com/embed/jtfu0ixxthy7运行演示: https://runkit.com/embed/jtfu0ixxthy7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.