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
0
: 243 At:- 6/20/2018 3:43:32 PM
C# UTC to Local datetime






1 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.

1
At:- 6/21/2018 6:26:17 PM
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





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