Javascript countdown using absolute timezone?

前端 未结 6 1632
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 17:19

I have a javascript countdown timer that works by taking a specified date and time, and comparing it to the current date and time. The issue is, the current time is relative

6条回答
  •  天涯浪人
    2020-12-01 17:53

    To revise the approach Brandon has taken to calculate a UTC-shifted time, we can slim the code down into a two-line extension of the Date object:

    /* getOffsetDate - Returns a Date shifted by a certain offset 
     * @param offset the UTC offset to shift, in hours
     * @return new date object shifted by UTC offset
     */
    Date.prototype.getOffsetDate = function( offset ) {
      utc = this.getTime() + (this.getTimezoneOffset() * 60000);
      return new Date(utc + (3600000*offset));
    }
    

    You can then calculate the UTC-5 shifted date as follows:

    myDate = new Date().getOffsetDate(-5); 
    

    It should be noted that extending native prototypes in this manner is generally considered a bad practice since it muddles core objects that other libraries depend upon. To justify it, you'd have to argue this functionality should be a native part of the Date object.

提交回复
热议问题