justicenation / slashclock

/clock concept as a new Slack app
GNU General Public License v3.0
0 stars 0 forks source link

DatetimeUtil.newDatetime wrong on DST transition dates #40

Open martyychang opened 6 years ago

martyychang commented 6 years ago

See question posted to Stack Exchange, "New Datetime instance on Daylight Savings Time transition date?"

martyychang commented 6 years ago

Below's a suggested solution from a friend

private static DateTime newDatetime(
        Date dateValue, Time timeValue, TimeZone zone) {            

    Datetime dtGMT = DateTime.newInstanceGmt(dateValue, timeValue);
    Integer originalOffset = -1 * zone.getOffset(dtGMT) / 1000; 

    // After adding the original offset, does the timezone still return the same number of seconds as offset? 
    return dtGMT.addSeconds(-1 * zone.getOffset(dtGMT.addSeconds(originalOffset)) / 1000);
}

And some comments to explain the code

your original method returns 5 hours offset because it was based on 3/12/2017 3am GMT (which is 3/11/2017 10pm EST) but at 3/12/2017 7am GMT (which is 3/12/2017 3am EDT), offset starts becoming 4 hours what my code does, is, it looks at 3/12/2017 8am GMT (which is 3/12/2017 3am GMT plus the assumed offset (5 hours)) and directly gets an offset value based on this 3/12/2017 8am GMT (which would be 4 hours) and use that new offset value directly on the original date/time