sunnuntai 8. huhtikuuta 2018

Keeping time 4: The hardest part


Everything we've handled so far in this series has been easy, compared to the real challenge that remains. Now that we got those parts ticking come the hard parts: Leap years and seconds, time zones, daylight savings time and date math.

Last of those meaning for example "how many days/hours/seconds is there between 30.4.1432 [julian] and 29.3.2018 [gregorian]"? Ok, I cheated here a bit, this is just about the hardest calculation you can imagine, and it's unlikely your device has to deal with such math... but again, it's better to at least acknowledge that such issues exist.

Most (well, essentially all) of the RTC chips out these just ignore all these (with exception of leap years - I think most handle them properly now) and leave them up to the application software to handle the rest. You might be tempted to handle them yourself, but there is this wisdom floating out there in the internet: "Thinking of writing your own calendar code? DON'T!"

So my first suggestion is to just to follow that piece of wisdom. Find a library that does that all to you, and use it with the constraints of the chip that you are using - the chips typically can handle normal calendar operations (like moving directly from 28.2. to 1.3.) and leap years (so month doesn't change on 28.2. but 29.2. on leap years) but not anything else. Leap seconds are kinda overkill, as your typical crystal won't be accurate enough for them to matter, but nevertheless, it's always good to keep such things in mind - if for nothing else, in case someone asks. It's always good to be prepared in such case.

But if you, despite of all this, choose to write your own routines, I have just one universal suggestion: Make your device to always use UTC, and handle all the translation on your "client" side. You'll still need a library, but if you happen to be making (for example) IoT device, you can push the hardest parts to the server where you do have libraries to do the heavy lifting for you.

Or you could just ignore all that. Make the device dumb enough not to even know of these and leave it to the user to handle them properly (manually set the clock after DST changes and so on.)

Otherwise, good luck on your chosen path. It will be a difficult journey, but it also will teach you many, many things that will help you further along the way.

Ei kommentteja:

Lähetä kommentti