Search code examples
javascriptdatelocaldatelocaltimetoisostring

Get the local date instead of UTC


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 something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring. What should I do ?

function nextWeekdayDate(date, day_in_week) {
  var ret = new Date(date || new Date());
  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('-');


Solution

  • 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)