What would be the best way to perform binary serialization of a date/time pair?
My best guess so far is to store the number of seconds since the epoch, as returned by the POSIX time() and mktime() functions, and then translate it back to “human readable” structures using localtime() upon retrieval.
Please note that timestamps will be stored and retrieved by computers in various timezones.
This depends some on what data, exactly, you’re interested in:
time_tgenerally doesn’t provide that, obviously, unless you use some sort of floating point type (which can introduce its own issues). Other languages’ and libraries’ time formats (such as JavaScript’s and Java’s) use milliseconds-since-a-fixed-date instead of seconds-since-a-fixed-epoch to address this.time_tor a JavaScript Data) is probably better than storing local time + a time zone.time_t, you’ll want to store it as a 64-bit number, not a 32-bit number. (Even if you store it as a 64-bit number, keep in mind that your C runtime’smktimeandlocaltimeimplementations may not support 64-bittime_tvalues.)Regarding the year 2038 problem in particular: I don’t know of any POSIX APIs that are guaranteed to handle it. If you want a library that’s guaranteed to handle it, you might be better off using something like
boost::date_time. The Project 2038 FAQ has information on testing your C runtime for 2038 support. According to that page, modern 64-bit Linux systems should not be affected. Recent versions of Visual C++ are also not affected. (See here.) Even if your libraries don’t currently support 64-bittime_tvalues, you can serialize a 64-bit int and cast it to 32 bits to process it; that way your on-disk data structures will at least be compliant, and your libraries will hopefully be updated before 2038 becomes a problem.