DateTime vs. DateTimeOffset — UtcNow vs. Now

BEN ABT
medialesson
Published in
2 min readSep 29, 2022

--

DateTime vs. DateTimeOffset — UtcNow vs. Now

.NET has two principal ways for handling times: DateTime and DateTimeOffset.

The big deficit of DateTime, which was also recognized early in .NET 1.0, is that it is not clear from the DateTime information which time zone the time information represents. Therefore DateTime is also called implicit representation of time information, whose “hope” is that the time information is always in relation to UTC-0. DateTime cannot guarantee this, which is why errors often occur in combination with time zones and DateTime. DateTime supports only two possibilities at this point: the local time of the application or UTC.

Since the problems of DateTime were recognized early, there was a much better alternative in the form of DateTimeOffset, which has been the recommended variant since .NET 1.1. Probably because DateTime appears in IntelliSense earlier than DateTimeOffset, this is often used despite the massive deficits and the huge error potential of DateTime.

But how do they differ at runtime?

Sustainable Code — DateTimeOffset vs. DateTime by https://github.com/BenjaminAbt/SustainableCode

It is not surprising that Now is slower than UtcNow, since the current time zone must be taken into account.
But overall DateTimeOffset is also more performant and thus needs less energy at runtime.

Not only the logical correctness and the lower error potential speak for DateTimeOffset, but also the performance.

These uses for DateTimeOffset values are much more common than those for DateTime values. As a result, consider DateTimeOffset as the default date and time type for application development.

Choose between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo

Autor

Benjamin Abt

Ben is a passionate developer and software architect and especially focused on .NET, cloud and IoT. In his professional he works on high-scalable platforms for IoT and Industry 4.0 focused on the next generation of connected industry based on Azure and .NET. He runs the largest german-speaking C# forum myCSharp.de, is the founder of the Azure UserGroup Stuttgart, a co-organizer of the AzureSaturday, runs his blog, participates in open source projects, speaks at various conferences and user groups and also has a bit free time. He is a Microsoft MVP since 2015 for .NET and Azure.

Originally published at https://schwabencode.com on September 29, 2022.

--

--