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

前端 未结 23 1117
爱一瞬间的悲伤
爱一瞬间的悲伤 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:05

    if you want to check the difference in a time between two dates, you can simply check if second timezone is lesser or greater from your first desired timezone and subtract or add a time.

      const currTimezone = new Date().getTimezoneOffset(); // your timezone
      const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone
    
      if (currTimezone !== newDateTimezone) {
        // and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
        const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
        date.setTime(date.getTime() + (newTimezone * 60 * 1000));
      }
    

提交回复
热议问题