Moment.js不显示本地日期和时间格式

时间:2019-12-20 15:58:17

标签: javascript momentjs

如果评论早于24小时,我试图为用户显示时间戳。以下代码可以做到这一点,但仍为我在巴基斯坦的开发人员显示我的(美国)日期和时间格式。应该显示dd / mm / yy而不是mm / dd / yy。它为什么不能正常工作?这是我的代码。

//get date of comment
          let commentDateUTC = item.createdOn;

          //convert it to local time
          let commentLocalTime = moment.utc(commentDateUTC).local().toLocaleString();

          //determine amount of time elapsed between comment and current time
          let nowObj = { 'now': moment(commentLocalTime).fromNow() }

          //determine if more than 24 hours has elapsed since the comment was created
          let currentTime = moment().local().toLocaleString();
          let elapsedTime = moment(currentTime).diff(commentLocalTime, 'hours');

          //if yes, concatenate the item.createdOn and the nowObj.now value
          if (elapsedTime >= 24) {
            nowObj.now = `${moment(commentLocalTime).format('l LT')} (${nowObj.now})`
          }

1 个答案:

答案 0 :(得分:2)

这就是答案。您必须从浏览器设置中获取语言环境,然后使用moment.locale();进行设置。我希望文档对此有所了解。...

      if (elapsedTime >= 24) {
        var locale = window.navigator.language;
        moment.locale(locale);
        nowObj.now = `${moment(commentLocalTime).format('l LT')} (${nowObj.now})`
      }