【问题标题】:moment js not showing local time it's showing same in the Database时刻js没有显示当地时间它在数据库中显示相同
【发布时间】:2022-01-08 20:47:00
【问题描述】:

如何根据本地时区显示 createdAt 字段日期。我已经尝试过,当我将它上传到显示 createdAt 字段数据 UTC 格式的服务器上时,它只适用于本地主机。

这是我的代码

dateFormatwithSec(date_time) {

    const testDateUtc = moment.utc(date_time);
    const localDate = moment(testDateUtc).local();
    return localDate.format('YYYY-MM-DD HH:mm:ss');
},

为什么它没有在服务器上提供正确的输出。

【问题讨论】:

  • 你在“上传到服务器”什么?大概是某种形式的时间戳。
  • 实际上,我有一个包含一些数据的行列表,例如 excel。我想根据用户位置和日期显示 DateTime。我正在使用续集 nodejs
  • 明确地说,date_time 的值究竟是多少?请注意,UTC 不是一种格式,而是一种时间标准。也许您的意思是 ISO 8601 格式,偏移量为 UTC(即 +0 或 Z),类似于“2021-12-03T03:16:16.037Z”。
  • date_time 得到这个值 2021-12-02 15:15:33 这个值来自我的 createdAt 单元格

标签: javascript node.js database datetime momentjs


【解决方案1】:

我从 RobG 那里找到了一个简单的解决方案。它非常适合我。我做了什么。

 function dateFormatwithSec (date_time) {
      const dateutc = date_time.replace('Z', '');
        //  console.log(dateutc);
        const dt = new Date(`${dateutc}Z`);
        const finaldate = moment(dt).format('L, h:mm ss a');
        //display local time with moment 
         console.log( "local time is - " , finaldate)
                 return finaldate ;
}


let ts = '2021-12-03T18:34:17.000Z';
dateFormatwithSec(ts);

"local time is - ", "12/04/2021, 12:04 17 am"

【讨论】:

    【解决方案2】:

    这不是一个答案,它实际上是一个扩展评论。 OP 应包含示例 date_time 字符串、OP 中的实际输出和预期输出,而不是 cmets。

    直到知道这一点,没有人能理解“它没有在服务器上提供正确的输出”是什么意思。

    这是对正在发生的事情的解释,希望对您有所帮助。

    Moment 的utc 方法使其将时间戳显示为UTC。对于解析,它仅在时间戳中没有偏移时才使用 UTC。因此,给定一个像“2021-12-02 15:15:33”这样的时间戳,它将返回一个时刻对象,其日期的时间值等于 2021-12-02T15:15:33+00:00。

    local 方法使 moment 以本地时区显示日期。请注意,“本地”是指根据系统设置,而不是系统的实际位置。

    考虑以下情况,其中添加了 Z 标记以显示该时刻用于对象的偏移量:

    function dateFormatwithSec (date_time) {
    
      // Set moment to UTC mode and parse the input string as UTC
      let testDateUtc = moment.utc(date_time);
      console.log('testDateUtc: ' + testDateUtc.format('YYYY-MM-DD HH:mm:ss Z'));
    
      // Set the moment object to local mode and return a formatted date
      let localDate = moment(testDateUtc).local();
      return localDate.format('YYYY-MM-DD HH:mm:ss Z');
    }
    
    let ts = '2021-12-02 15:15:33+04:00';
    console.log('localDate  : '+ dateFormatwithSec(ts));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    附言。解析字符串时,最好也提供格式,所以:

    moment.utc(date_time, 'YYYY-MM-DD HH:mm:ss')
    

    是首选。它还允许维护人员查看预期的格式(尽管它也应该在文档中)。即使是对格式的非常小的更改也会导致时刻回退到实现的内置解析器,例如“2021-12-02 15:15:33+04:00”与“2021-12-02 15:15:33 +04:00”。

    【讨论】:

    • 非常感谢,足以解决我的问题。
    • 请查看我编写的代码并告诉我您的反馈。
    猜你喜欢
    • 1970-01-01
    • 2021-01-31
    • 2017-12-24
    • 2021-08-22
    • 1970-01-01
    • 2022-11-19
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多