Created
July 14, 2015 00:27
-
-
Save jamesinc/801f9d42cef3c5469ef3 to your computer and use it in GitHub Desktop.
Calculate correct current AEST/ADST time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var getCurrentAestDate = function ( ) { | |
var d = new Date(), | |
timezone = 10, | |
utc = d.getTime() - ( d.getTimezoneOffset() * 60000 ), | |
// Current +10 (AEST) time | |
aest = new Date( utc + (3600000 * -timezone) ), | |
// Current +11 (ADST) time | |
adst = new Date( utc + (3600000 * -(timezone+1)) ), | |
// Set to start of the month DST starts (October) | |
// and time of rollover (0200) | |
dstStart = new Date(aest.getFullYear(), (10-1), 1, 2, 0, 0, 0), | |
// Set to start of the month DST ends (April) | |
// and time of rollover (0300) | |
dstEnd = new Date(aest.getFullYear(), (04-1), 1, 3, 0, 0, 0); | |
// Now, calculate the position of the first Sunday of the start and end month, | |
// which is when DST actually starts, or ends. | |
// One of 1001 great uses for mod! | |
dstStart.setDate( dstStart.getDate() + ((7 - dstStart.getDay()) % 7) ); | |
dstEnd.setDate( dstEnd.getDate() + ((7 - dstEnd.getDate()) % 7) ); | |
// Now we simply check if the current date is between the two regions | |
// If ADST is after the end datetime and AEST is before the start datetime, | |
// then DST is not in effect. You have to think about this one a little bit... | |
// it matters which clock you check, otherwise you might have incorrect 1 hour | |
// edge cases around the start/end datetimes. | |
// An alternative and perhaps easier way to calculate all this would be to just | |
// work everything out against UTC and do away with the need for two Dates. | |
if ( adst.getTime() > dstEnd.getTime() && aest.getTime() < dstStart.getTime() ) { | |
// No DST! | |
return aest; | |
} | |
// Yes, DST! | |
return adst; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment