C#: DateTime to UTC to Milliseconds

If you need to create a universal timestamp which can be sent between servers which may live in different timezones the best way to do this is to make sure you are using the Universal Time standard or UTC. Once you are using the UTC all servers evaluating the timestamp will be able to read in the UTC time and compare it against their UTC and determine if the timestamp has exceeded its limit.

Another issue along the same lines was the service we were calling was not only looking for a UTC time for its timestamps but also wanted that time in the form of milliseconds. Unfortunately there is no built in method on the DateTime Object for converting the current time to milliseconds. In order to get around this you have to do a trick using the total ticks from the DateTime object and then using a property of the TimeSpan object called TicksPerMillisecond. If you divide the ticks by the TicksPerMillisecond property you get the total miliseconds for the current time.

Example:

DateTime.Now.ToUniversalTime().Ticks / TimeSpan.TicksPerMillisecond

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s