kamiar3001
kamiar3001

Reputation: 2676

How I can convert UTC date to my time-zone?

I need to convert time to "UTC+03:30 Time Zone" in my web application here is UTC date :

DateTime dt = DateTime.UtcNow;

Is there any function to convert UTC to my time zone or not ? I don't want to involve myself writing a new function in my application if there is a function in ASP.NET.

The application might be hosted in different server in the world and that's exactly why I have used UTC date.

I need a function to add 3:30 to the current UTC time.

Upvotes: 4

Views: 2958

Answers (2)

jamiegs
jamiegs

Reputation: 1791

this would let you convert UTC to any timezone

Shared Function FromUTC(ByVal d As Date, ByVal tz As String) As Date
 Return (TimeZoneInfo.ConvertTimeBySystemTimeZoneId(d, TimeZoneInfo.Utc.Id, tz))
end function

you're able to get the list of timezones using

For Each timeZone As TimeZoneInfo In tzCollection
   Console.WriteLine("   {0}: {1}", timeZone.Id, timeZone.DisplayName)
Next

Upvotes: -1

Jon Skeet
Jon Skeet

Reputation: 1499760

Are you sure your time zone is really UTC +3:30, all the time, with no daylight savings? If so, you could create a DateTimeOffset with the appropriate offset (3.5 hours). For example:

DateTimeOffset dtOffset = new DateTimeOffset(DateTime.UtcNow,
                                             TimeSpan.FromHours(3.5));

Of course that gives you a DateTimeOffset instead of a DateTime... are you able to use that?

A better solution is to use TimeZoneInfo - for example, you could get the right time zone and call

DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, tzInfo);

... or you could use TimeZoneInfo but still get a DateTimeOffset:

DateTimeOffset dto = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, tzInfo);

Personally I would recommend you use DateTimeOffset if you can, as the meaning of DateTime is somewhat ambiguous and hard to work with correctly.

.NET's date and time handling is a bit of a mess, unfortunately :( I have a project called Noda Time which should improve the state of affairs if we ever complete it, but it's far from production-ready at the moment.

Upvotes: 7

Related Questions