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.
Here are the possible methods to convert UTC time into Local using C#
TimeZone.CurrentTimeZone.ToLocalTime(UTCDateTime);
UTCDateTime.ToLocalTime();
(Should work)
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
TimeZoneInfo.ConvertTimeFromUtc(UTCDatetime, TimeZoneInfo.Local)
Any of the above ways should work, easiest is to use .ToLocalTime()
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.
You can also try
@TimeZoneInfo.ConvertTimeFromUtc(UTCTime, TimeZoneInfo.Local)
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly