Avatar for PaulH

PaulH

Member since Jun 2019 • Last active Jul 2019
  • 0 conversations
  • 1 comments

Most recent activity

  • in JavaScript
    Avatar for PaulH

    Maybe this could help others searching for DST stuff (for Europe at least):

    
    var offsetUTC = 1; // the offset to UTC in Standard Time (winter)
    var useDST = true; // if true, DST will be taken into account when setting TZ
    
    // these formulae are valid until 2099 (or 2022  https://en.wikipedia.org/wiki/Summer_tim­e_in_Europe
    function dayEndWinter(year) { // last Sunday of March
            return Math.ceil(31 - ((((5 * year) / 4) + 4) % 7));
    }
    
    function dayEndSummer(year) { // last Sunday of October
            return Math.ceil(31 - ((((5 * year) / 4) + 1) % 7));
    }
    
    function checkDST(date) {
    
            let year = date.getFullYear();
            let dateStart = new Date(`${year}-03-${dayEndWinter(year)}T0­1:00:00 GMT`);
            let dateEnd = new Date(`${year}-10-${dayEndSummer(year)}T0­1:00:00 GMT`);
      
            return (date >= dateStart && date < dateEnd);
      
    }
    
    function setTimeZone(offsetUTC, useDST) {
            E.setTimeZone(0); // start with UTC
            if (useDST && checkDST(new Date())) {
                offsetUTC += 1; // we're in DST
            }
            E.setTimeZone(offsetUTC);
            console.log('Time after setting TZ: ' + (new Date()).toString());
    }
    
    // sets the TZ with respect to DST
    setTimeZone(offsetUTC, useDST);
    
    // get some start and end dates
    for (let y=2018;y<2023;y++) {
            let dateStart = new Date(`${y}-03-${dayEndWinter(y)}T01:00:0­0 GMT`);
            let dateEnd = new Date(`${y}-10-${dayEndSummer(y)}T01:00:0­0 GMT`);
            console.log(dateStart.toUTCString() + ' till ' + dateEnd.toUTCString());
    }
    
    // test some dates
    let dateStrings = [
            '2019-01-01T00:01:00 GMT', // DST false
            '2019-03-31T00:01:00 GMT', // DST false
            '2019-03-31T02:01:00 GMT', // DST true
            '2019-08-01T00:01:00 GMT', // DST true
            '2019-10-27T00:01:00 GMT', // DST true
            '2019-10-27T01:01:00 GMT', // DST false
            '2019-12-01T00:01:00 GMT', // DST false
    ];
    dateStrings.forEach(function (dateString) {
            let date = new Date(dateString);
            console.log('Checking date ' + date.toString() + ': ' + checkDST(date));
    })
    
    
Actions