Get the local date instead of UTC

前端 未结 2 1319
野性不改
野性不改 2021-01-26 18:01

The following script calculates me next Friday and next Sunday date.

The problem : the use of .toISOString uses UTC time. I need to change with somethin

2条回答
  •  甜味超标
    2021-01-26 18:47

    If you worry that the date is wrong in some timezones, try normalising the time

    To NOT use toISO you can do this

    const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', 
      { year: 'numeric', month: '2-digit', day: '2-digit' })
      .split("/")
    

    function nextWeekdayDate(date, day_in_week) {
      var ret = new Date(date || new Date());
      ret.setHours(15, 0, 0, 0); // normalise
      ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
      return ret;
    }
    
    let nextFriday = nextWeekdayDate(null, 5);
    let followingSunday = nextWeekdayDate(nextFriday, 0);
    
    console.log('Next Friday     : ' + nextFriday.toDateString() +
      '\nFollowing Sunday: ' + followingSunday.toDateString());
    
    /* Previous code calculates next friday and next sunday dates */
    
    
    var checkinf = nextWeekdayDate(null, 5);
    var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
    var checkouts = nextWeekdayDate(null, 7);
    var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
    
    console.log(yyyy, mm, dd)
    
    // not using UTC: 
    
    const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
    
    console.log(yyyy1, mm1, dd1)

提交回复
热议问题