how to convert UTC time to Local using C#?


Hello, I would like to know how can I convert UTC datetime into local (user's pc) datetime in asp.net MVC razor page using C#?

I thought .ToLocalTime() should work, but I am not getting correct result.


Asked by:- Vinnu
2
: 14259 At:- 6/20/2018 3:43:32 PM
C# UTC to Local datetime







3 Answers
profileImage Answered by:- pika

Here are the possible methods to convert UTC time into Local using C#

  1. Using TimeZone.CurrentTimeZone.ToLocalTime(UTCDateTime);
  2. Using UTCDateTime.ToLocalTime(); (Should work)
  3. When Format is known using DateTime.ParseExact
    1. DateTime.ParseExact(dateString, 
                         "MM/dd/yyyy HH:mm:ss", 
                         CultureInfo.InvariantCulture, 
                         DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)

      In the above code, we have considered that Datetime format is known to us

  4. Using TimeZoneInfo.ConvertTimeFromUtc(UTCDatetime, TimeZoneInfo.Local)

Any of the above ways should work, easiest is to use .ToLocalTime()

2
At:- 6/21/2018 6:26:17 PM Updated at:- 9/27/2022 7:39:08 AM
Excellent answer, Yes .ToLocalTime() was working for me, after implementing all other alternatives, which is showing result as .ToLocalTime, I got to know my datetime was already convert into local from UTC. 0
By : Vinnu - at :- 6/23/2018 7:36:37 AM


profileImage Answered by:- vikas_jk

You can also try something like this

// Coordinated Universal Time string from 
		// DateTime.Now.ToUniversalTime().ToString("u");
		string date = "2022-02-11 16:13:00Z"; 
		// Local .NET timeZone.
		DateTime localDateTime = DateTime.Parse(date); 
		DateTime utcDateTime = localDateTime.ToUniversalTime();


		string meTimeZoneKey = "Middle East Standard Time";
		TimeZoneInfo meTimeZone = TimeZoneInfo.FindSystemTimeZoneById(meTimeZoneKey);
		DateTime meDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, meTimeZone);
		Console.WriteLine(meDateTime); 


//output: 2/11/2022 6:13:00 PM

Fiddle link: https://dotnetfiddle.net/fu7R8r

Thanks.

1
At:- 3/11/2022 10:45:02 AM
Good detailed answer, thanks 0
By : pika - at :- 6/3/2022 10:50:23 AM


profileImage Answered by:- jaiprakash

You can also try

@TimeZoneInfo.ConvertTimeFromUtc(UTCTime, TimeZoneInfo.Local)

Thanks.

0
At:- 11/15/2022 3:01:36 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use