Timestamp Converters: Handling Seconds, Milliseconds, and Zones
Unix timestamps are unreadable until converted, and conversions break on units, zones, and daylight saving. Here is how I handle them. Unix timestamps are everywhere in programming. Databases store them, APIs return them, logs are full of them. A timestamp is a single integer that represents a moment in time, and it is completely unreadable to humans. The number 1753000000 means nothing to me until I convert it to a date. A timestamp converter is the tool I use to bridge that gap, and after years of debugging time-related bugs, I have a clear understanding of where the conversions go wrong. Know Your Units: Seconds Versus Milliseconds The most common timestamp bug is a unit mismatch. Unix timestamps come in seconds and in milliseconds. A seconds timestamp is ten digits for current dates. A milliseconds timestamp is thirteen digits. JavaScript uses milliseconds. Python and most server-side languages use seconds. When data crosses between them, the unit often does not, and the result is a date thousands of years in the future or in 1970. I check the digit count before converting. A ten-digit number is seconds. A thirteen-digit number is milliseconds. If I have ten digits and the converter expects milliseconds, I multiply by one thousand. More tutorials are on the KitCraft Blog.