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

Published by

Unknown's avatar

Tim Clark

Experienced Business Owner, Chief Information Officer, Vice President, Chief Software Architect, Application Architect, Project Manager, Software Developer, Senior Web Developer, Graphic Designer & 3D Modeler, University Instructor, University Program Chair, Academic Director. Specialties: Ruby, Ruby on Rails, JavaScript, JQuery, AJAX, Node.js, React.js, Angular.js, MySQL, PostgreSQL, MongoDB, SQL Server, Responsive Design, HTML5, XHTML, CSS3, C#, ASP.net, Project Management, System Design/Architecture, Web Design, Web Development, Adobe CS6 (Photoshop, Illustrator)

Leave a comment