Create a Date with a set timezone without using a string representation

前端 未结 23 1599
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 01:48

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date obje

23条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 02:00

    SOLVED:

    When I create a date object:

    new Date(year, month, day, hour, minute)

    I works fine on localhost. When I deploy to server it breaks, because server is in another timezone.

    I can't use getTimezoneOffset(). I need the timezoneOffset of my home - dependent on summertime/wintertime

    // add diff minutes between myself (HOME) and server 
    timezoneHomeOffset (d, tz = 'Europe/Copenhagen') {
      const utc = new Date(d.getTime())
      const dHome = new Date(d.toLocaleString('en-US', { timeZone: tz }))
      const diff = Math.round((utc - dHome) / 60000) // 60*1000 => minutes
      d.setMinutes(d.getMinutes() + diff)
      return d
    }
    

提交回复
热议问题