Asp net core utc time to local

ASP.NET is a popular programming language used for developing web . One common requirement in web is to convert UTC time to local time in ASP.NET Core. In this article, we will explore approaches to achieve this conversion with examples.

Approach 1: Using TimeZoneInfo.ConvertTimeFromUtc

One way to convert UTC time to local time in ASP.NET Core is by using the TimeZoneInfo.ConvertTimeFromUtc method. This method takes a value representing the UTC time and converts it to the local time based on the system's time zone settings.


DateTime utcTime = DateTime.UtcNow;
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, TimeZoneInfo.Local);

In the above example, we first get the current UTC time using DateTime.UtcNow. Then, we use the TimeZoneInfo.ConvertTimeFromUtc method to convert the UTC time to the local time based on the system's time zone settings. The local time is in the localTime variable.

Approach 2: Using DateTimeOffset

approach to convert UTC time to local time in ASP.NET Core is by using the DateTimeOffset structure. The DateTimeOffset structure represents a point in time along with an offset that indicates the difference that time and Coordinated Time (UTC).


DateTimeOffset utcTime = DateTimeOffset.UtcNow;
DateTimeOffset localTime = utcTime.ToLocalTime();

In the above example, we first get the current UTC time using DateTimeOffset.UtcNow. Then, we use the ToLocalTime method to convert the UTC time to the local time based on the system's time zone settings. The converted local time is stored in the localTime variable.

Approach 3: Using TimeZoneInfo.FindSystemTimeZoneById

If you want to convert UTC time to a specific time zone other than the system's time zone, you can use the TimeZoneInfo.FindSystemTimeZoneById method. This method takes a time zone identifier as a parameter and returns a TimeZoneInfo object representing that time zone.


DateTime utcTime = DateTime.UtcNow;
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, timeZone);

In the above example, we first get the current UTC time using DateTime.UtcNow. Then, we use the TimeZoneInfo.FindSystemTimeZoneById method to get the TimeZoneInfo object representing the “Pacific Standard Time” time zone. Finally, we use the TimeZoneInfo.ConvertTimeFromUtc method to convert the UTC time to the local time in the specified time zone.

These are some of the approaches you can use to convert UTC time to local time in ASP.NET Core. Choose the approach that best suits your requirements and it in your web application.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents