【问题标题】:How to convert a UTC string into a momentJS in visitor's local timezone?如何将 UTC 字符串转换为访问者本地时区的 momentJS?
【发布时间】:2016-05-05 07:41:23
【问题描述】:

我有以下 Javascript 字符串,它表示协调世界时 (UTC) 中的某个时刻:

myUTCString = "2014-11-06 00:00:00";

我想使用 moment.js 将此字符串转换为本地化到访问者浏览器时区的时刻。我该怎么做?

我试过了:

moment(moment.utc("2014-11-06 00:00:00")).local()

但它给了我这个:

如您所见,该对象不包含属性_d 向我显示本地化时间的字符串值。但这不是我需要的。我需要一个本地时间的实际时刻对象,以便稍后在我的代码中进一步操作/使用它。如何做呢?这似乎是非常普遍需要的东西。

【问题讨论】:

    标签: javascript angularjs momentjs


    【解决方案1】:

    有一种更简单的方法可以做到这一点。

    如果您知道自己有一个 UTC 日期,并且希望将其转换为用户的本地时间,只需执行以下操作:

    moment.utc("2014-11-06 00:00:00").local()
    

    这会产生用户当地时间的片刻。此时.format()的结果将是用户当地时间。

    不要看_d 的值。这是不准确的。请参阅以下内容:http://momentjs.com/guides/#/lib-concepts/internal-properties/

    【讨论】:

      【解决方案2】:

      我找到了这个小提琴:https://jsfiddle.net/FLhpq/4/

      UTC<br/>
      <div id="divUTC"></div><br/>
        Your Local Time with respect to above UTC time<br/>
      <div id="divLocal">
      </div>
      
      $(function(){
           setInterval(function(){
               var divUtc = $('#divUTC');
               var divLocal = $('#divLocal');  
               //put UTC time into divUTC  
               divUtc.text(moment.utc().format('YYYY-MM-DD HH:mm:ss'));      
      
               //get text from divUTC and conver to local timezone  
               var localTime  = moment.utc(divUtc.text()).toDate();
               localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
               divLocal.text(localTime);        
           },1000);
      });
      

      我希望这正是您所需要的 - 字符串中的 utc 时间被转换为本地化时间。

      【讨论】:

      • 我从那个小提琴中提取的正确答案:moment(moment.utc(myUTCString).toDate())
      • 这是迄今为止关于此 UTC 到本地时间转换的最佳答案。 moment.utc("2014-11-06 00:00:00").local() 似乎对我不起作用。
      猜你喜欢
      • 2019-02-22
      • 1970-01-01
      • 2010-09-09
      • 2022-11-23
      • 1970-01-01
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 2018-02-23
      相关资源
      最近更新 更多