Javascript 获取经过的时间,考虑用户';有时刻的时区
我正在用React Native做一个web应用程序来显示事件列表。这些事件来自一个后端,配置为GMT-4,位于美国/圣多明各时区 我从后端收到的事件日期是Javascript 获取经过的时间,考虑用户';有时刻的时区,javascript,moment-timezone,Javascript,Moment Timezone,我正在用React Native做一个web应用程序来显示事件列表。这些事件来自一个后端,配置为GMT-4,位于美国/圣多明各时区 我从后端收到的事件日期是2020-11-05T16:02:13.1018115 我的事件屏幕如下所示: Title: Hi, a party has started! Description: 1 hour ago // <= could be year, month, day, hour, minute or second 此函数用于处理转换: expor
2020-11-05T16:02:13.1018115
我的事件屏幕如下所示:
Title: Hi, a party has started!
Description: 1 hour ago // <= could be year, month, day, hour, minute or second
此函数用于处理转换:
export const formatTimeByOffset = (dateString, offset) => {
// Params:
// How the backend sends me a timestamp
// dateString: on the form yyyy-mm-dd hh:mm:ss
// offset: the amount of hours to add.
// If we pass anything falsy return empty string
if (!dateString) return '';
if (dateString.length === 0) return '';
// Step 1: Parse the backend date string
// Get Parameters needed to create a new date object
const year = dateString.slice(0, 4);
const month = dateString.slice(5, 7);
const day = dateString.slice(8, 10);
const hour = dateString.slice(11, 13);
const minute = dateString.slice(14, 16);
const second = dateString.slice(17, 19);
// Step: 2 Make a JS date object with the data
const dateObject = new Date(`${year}-${month}-${day}T${hour}:${minute}:${second}`);
// Step 3: Get the current hours from the object
const currentHours = dateObject.getHours();
// Step 4: Add the offset to the date object
dateObject.setHours(currentHours + offset);
// Step 5: stringify the date object, replace the T with a space and slice off the seconds.
const newDateString = dateObject
.toISOString()
.replace('T', ' ')
.slice(0, 19);
// Step 6: Return the new formatted date string with the added offset
return `${newDateString}`;
}
一些用户看到1-4小时之间的差异
例如:
Today: Thu Nov 05 2020 19:0803 GMT-0400
Date from backend: 2020-11-05T16:27:40.687
Date converted to local time using the function above: 2020-11-05 12:27:40
Result: 6 hours // <= Has an extra hour
今天:2020年11月5日星期四19:0803 GMT-0400
后端日期:2020-11-05T16:27:40.687
使用上述功能转换为当地时间的日期:2020-11-05 12:27:40
结果:6小时/试试这个
var localTime = moment.utc("2020-11-05T16:02:13.1018115").add(4, 'hour').local().fromNow();
您能否解释一下您的建议是如何考虑用户的时区的,以及为什么要添加-4小时?服务器上设置的时区通常为gmt 0,但正如您所说,后端配置为gmt-4,因此我添加了-4以设置gmt时间,然后将gmt转换为本地时间。请试试这个,我不确定它是否会工作,但你可以试试,这是我的建议,明白了,原来服务器时间正在使用EST,所以我们在4,而不是-4。我刚刚更改了你的代码,将其添加为4小时而不是-4小时。它工作得很好。很高兴只有一条线来完成我的目标。谢谢。
var localTime = moment.utc("2020-11-05T16:02:13.1018115").add(4, 'hour').local().fromNow();