【问题标题】:Get timezone and date of browser from date object从日期对象获取浏览器的时区和日期
【发布时间】:2016-12-13 16:25:51
【问题描述】:

我在 javascript 中有这个日期对象。

var d = new Date();

以上代码行将在 Chrome 浏览器上运行。我想提取浏览器的日期(例如:2016 年 12 月 14 日)和时区(例如:GMT+0800)等信息。

【问题讨论】:

    标签: javascript date time


    【解决方案1】:

    根据MDN documentationgetTimezoneOffset 应该能够为您获取时区。

    var d = new Date();
    d.getTimezoneOffset(); // returns offset in minutes
    

    至于格式化日期,moment.js 是一个预先存在的库,它使日期和时间格式化比它需要的跨浏览器支持更痛苦。

    【讨论】:

      【解决方案2】:

      你可以这样做:

      var now = new Date();
      
      document.write(now.toUTCString() + "<br>")
      document.write(now.toTimeString() + "<br>")
      

      其他一些属性是:

      toDateString()  Converts the date portion of a Date object into a readable string
      toGMTString()   Deprecated. Use the toUTCString() method instead
      toISOString()   Returns the date as a string, using the ISO standard
      toJSON()    Returns the date as a string, formatted as a JSON date
      toLocaleDateString()    Returns the date portion of a Date object as a string, using locale conventions
      toLocaleTimeString()    Returns the time portion of a Date object as a string, using locale conventions
      toLocaleString()    Converts a Date object to a string, using locale conventions
      toString()  Converts a Date object to a string
      toTimeString()  Converts the time portion of a Date object to a string
      toUTCString() Converts a Date object to a string, according to universal time
      

      您甚至可以使用moment.js 插件来帮助您解决这个问题。它使所有这些任务变得微不足道。

      还要获取时区偏移量,请使用类似:

      getTimezoneOffset(); 
      

      【讨论】:

        【解决方案3】:

        类似这样的:

        var d = new Date();
        var n = d.getTime();
        

        或者这个:

        if (!Date.now) {
          Date.now = function now() {
            return new Date().getTime();
          };
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-18
          • 1970-01-01
          • 2022-10-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多