developer
developer

Reputation: 3871

convert utc time and offset to DateTime

i have a datetime(in utc) saved in database and i also know the utc offset in the following format.

-03:00:00

how to convert this to a DateTime

Upvotes: 5

Views: 14401

Answers (2)

Arne Claassen
Arne Claassen

Reputation: 14404

The problem you are likely running into is that most DB drivers when fetching from the database will create the DateTime with DateTimeKind.Unspecified, which may not convert to UTC properly even when you use ToUniversalTime. To get arround this I use an extension method like this:

    public static DateTime ToSafeUniversalTime(this DateTime date) {
        if(date != DateTime.MinValue && date != DateTime.MaxValue) {
            switch(date.Kind) {
            case DateTimeKind.Unspecified:
                date = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, DateTimeKind.Utc);
                break;
            case DateTimeKind.Local:
                date = date.ToUniversalTime();
                break;
            }
        }
        return date;
    }

Upvotes: 0

CraigTP
CraigTP

Reputation: 44919

This simplest way to apply an "offset" to a DateTime that you already have is to create a TimeSpan structure which holds your offset value, and then simply "add" the offset to the original DateTime value.

For example:

DateTime utcDateTime = DateTime.Parse("29 July 2010 14:13:45");
TimeSpan offSet = TimeSpan.Parse("-03:00:00");
DateTime newDateTime = utcDateTime + offSet;
Console.WriteLine(newDateTime);

This results in the following output:

29/07/2010 11:13:45

which is the original time (29 July 2010 14:13:45) minus 3 hours (the offset - -03:00:00).

Note that this technique is merely performing simple arithmetic with your DateTime value and does not take any time zones into account.

Upvotes: 18

Related Questions