Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UTC DateTime to Local DateTime in C#

I want to show Date & Time of an event which will be managed according to time zone of user. To check time zone I change my system time Zone to another time zone but my code is still getting Local time Zone. Here's My code

I am using Cassendra Database and C# .NET MVC

DateTime startTimeFormate = x.Startdate;
DateTime endTimeFormate = x.Enddate;
TimeZone zone = TimeZone.CurrentTimeZone;
DateTime startTime = zone.ToLocalTime(startTimeFormate);
DateTime endTime = zone.ToLocalTime(endTimeFormate);
like image 602
Champ Prateek Avatar asked Jan 02 '23 09:01

Champ Prateek


1 Answers

To convert the UTC DateTime to your Local DateTime, you have to use TimeZoneInfo as follows:

DateTime startTimeFormate = x.Startdate; // This  is utc date time
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(startTimeFormate, systemTimeZone);

Moreover if you want to convert UTC DateTime to user specific Local DateTime then do as follows:

string userTimeZoneId = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneId);
DateTime userLocalDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, userTimeZoneId);

Note: TimeZone in .NET is obsolete now and it has been deprecated. Instead use TimeZoneInfo.

like image 133
TanvirArjel Avatar answered Jan 12 '23 16:01

TanvirArjel