Converting Timestamps

My current project has me converting dates and times to and from timestamps. It’s really just adding and subtracting once you get down to it, but there are still some bits worth sharing.

What Are Timestamps?

When programmers say “timestamp”, they’re almost always referring to the Unix timestamp. The Unix epoch is midnight of January 1, 1970, so a timestamp is simply the number of seconds that have passed since that moment in time.

Always Start With UTC

Timestamps should always be calculated from coordinated universal time, or UTC for short (if you’re curious, this is why it’s not CUT). UTC is mostly the same as Greenwich Median Time (GMT), except GMT honors daylight savings time while UTC does not. There’s more to it of course, but it’s all very mind-numbing and not worth getting into at the moment. Just know that UTC gives us a nice consistent reference point to count the seconds.

So if your timestamps are based on UTC, then you need to make sure you’re using UTC and not your local time. It’s super easy to get the current date/time in UTC in C#:

DateTime myDateTime = DateTime.UtcNow;

Or if you already have a local DateTime and need to convert it to UTC:

myDateTime = myDateTime.ToUniversalTime();

Converting DateTime To Timestamp

Now that you have a proper UTC DateTime, you can convert it to a timestamp with this:

DateTime epoch = new DateTime(1970, 1, 1);
TimeSpan span = myDateTime.Subtract(epoch);
double timestamp = span.TotalSeconds;

Converting Timestamp To DateTime

If you want to go the other way and convert a timestamp to a DateTime, use this:

DateTime epoch = new DateTime(1970, 1, 1);
DateTime myDateTime = epoch.AddSeconds(myTimestamp);

Simple enough.

Hey, you reached the end!

Feel free to check out my other blog posts or subscribe to my RSS feed. You can also click a tag below to see related blog posts.