Last active
April 24, 2024 18:52
-
-
Save ngxson/1c8fb6fbb825b07aab8fe199991ca536 to your computer and use it in GitHub Desktop.
ESP32Time time offset table
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
/** | |
* This file calculates a lookup table for all the day that daylight saving take effect. | |
* The output file is a hpp file, which can use used in Arduino project. | |
* If you don't have nodejs on your machine, you can use an online compiler, for example: https://www.tutorialspoint.com/execute_nodejs_online.php | |
*/ | |
// number of years in the future to generate | |
const NB_OF_YEARS = 20; | |
// set the current timezone | |
const TZ = 'Europe/Paris'; | |
process.env.TZ = TZ; | |
const now = new Date(); | |
now.setHours(0); | |
now.setMinutes(0); | |
now.setSeconds(0); | |
now.setMilliseconds(1); | |
const endYear = now.getFullYear() + NB_OF_YEARS; | |
const timeOffsetTable = []; | |
const addNewOffsetEntry = () => { | |
const offsetInt = now.getTimezoneOffset() * -1 * 60; | |
console.log(`New time offset entry: ${now.toISOString()} - Offset: ${offsetInt}`); | |
timeOffsetTable.push({ | |
time: (now.getTime() - 1) / 1000, | |
offset: offsetInt, | |
comment: now.toISOString(), | |
}); | |
}; | |
addNewOffsetEntry(); // add the current entry | |
let lastOffset = now.getTimezoneOffset(); | |
while (now.getFullYear() <= endYear) { | |
const ONE_HOUR = 60 * 60 * 1000; | |
now.setTime(now.getTime() + ONE_HOUR); | |
if (now.getTimezoneOffset() !== lastOffset) { | |
lastOffset = now.getTimezoneOffset(); | |
addNewOffsetEntry(); | |
} | |
} | |
const CPP_CODE = ` | |
#define timeOffsetTableSize ${timeOffsetTable.length} | |
unsigned long timeOffsetTable[${timeOffsetTable.length}][2] = { | |
${timeOffsetTable.map(entry => ` {${entry.time}, ${entry.offset}}, // ${entry.comment}`).join('\n')} | |
}; | |
// Get the current offset. Please use ESP32Time.getLocalEpoch() to get the currentEpoch | |
long getTimeOffset(unsigned long currentEpoch) { | |
for (int i = timeOffsetTableSize - 1; i >= 0; i--) { | |
unsigned long time = timeOffsetTable[i][0]; | |
unsigned long offset = timeOffsetTable[i][1]; | |
if (time <= currentEpoch) { | |
return offset; | |
} | |
} | |
return 0; // default, should never happen | |
} | |
/** | |
* To use it: | |
* ESP32Time rtc(0); | |
* rtc.setTime(epochTime); // epochTime maybe fetched from internet using NTP | |
* | |
* Then before you read the time: | |
* rtc.offset = getTimeOffset(rtc.getLocalEpoch()); | |
* | |
* Then just read the time as normal: | |
* int hour = rtc.getHour(true); // true for 24h format | |
* int minute = rtc.getMinute(); | |
*/ | |
`; | |
console.log(CPP_CODE); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment