考虑到用户的TimeZone with Moment,获取已过去的时间

问题描述

我正在React Native中做一个Web应用程序以显示事件列表。这些事件来自配置为 GMT -4 的后端,该后端位于America / Santo_Domingo,为TimeZone。

我从后端收到的事件的日期是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

问题:当我执行new Date()进行计算时,某些设备会报告不同的日期。这些日期有几个小时的差异。例如,使用时区America/La_PazEtc/GMT+12的设备。

我的结论是,我需要考虑设备的时区来进行计算。我正在关注this guide,并且已经安装了Moment Timezone

我将从后端收到的日期传递给此函数:

 export const timeSince = (backEndTimeStamp) => {

   // get device timezone eg. -> "America/La_Paz"
   const deviceTimeZone = 'America/La_Paz';

   // Make moment of right now,using the device timezone
   const today = moment().tz(deviceTimeZone);

   // Get the UTC offset in hours
   const currentTimeZoneOffsetInHours = today.utcOffset() / 60;

   const convertedToLocalTime = formatTimeByOffset(backEndTimeStamp,currentTimeZoneOffsetInHours);

   const years = today.diff(convertedToLocalTime,'years');
   const months = today.diff(convertedToLocalTime,'months');
   const days = today.diff(convertedToLocalTime,'days');
   const hours = today.diff(convertedToLocalTime,'hours');
   const minutes = today.diff(convertedToLocalTime,'minutes');
   const seconds = today.diff(convertedToLocalTime,'seconds');

   let timeDiff = '';
   if (years > 0) {
     timeDiff = years + (years === 1 ? ' year' : ' years');
   } else if (months > 0) {
     timeDiff = months + (months === 1 ? ' month' : ' months');
   } else if (days > 0) {
     timeDiff = days + (days === 1 ? ' day' : ' days');
   } else if (hours > 0) {
     timeDiff = hours + (hours === 1 ? ' hour' : ' hours');
   } else if (minutes > 0) {
     timeDiff = minutes + (minutes === 1 ? ' minute' : ' minutes');
   } else if (seconds > 0) {
     timeDiff = seconds + (seconds === 1 ? ' second' : ' seconds');
   } else {
     timeDiff = 'unknown';
   }

   return timeDiff;
  }

此函数处理转换:

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

我尝试了很多事情,我有点困惑。

我的目标是考虑到用户的timeZone,获取已经过去的时间。知道后端使用GMT -4向我发送了日期。

感谢您的帮助。

解决方法

尝试

var localTime = moment.utc("2020-11-05T16:02:13.1018115").add(4,'hour').local().fromNow();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...