Get the local date instead of UTC

前端 未结 2 1291
野性不改
野性不改 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:36

    You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?

    The nextFriday is a date object. Would it work if you use the get-functions instead? e.g.

    const nextFridayYear = nextFriday.getFullYear();
    // get month is zero index based, i have added one
    const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
        .padStart(2, '0');
    const nextFridayDay = today.getDate().toString()
        .padStart(2, '0');
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题