DaD
DaD

Reputation: 95

Convert datetime to string always defaults to system time zone offset, Need to get the users timezone offset in the result

I have a code where the user enters the DateTime and the timezone in which the dates needs to be converted to and the format in which the end date should be. Below is the code.

The code converts the DateTime perfectly to the timezone the user has entered but when formatting the Datetime, the date time offset value is always defaulted to the systems time zone offset. For example when I convert the Date 2014-10-30T08:01:01-06:00(central time) to pacific standard time and format it. The result is 2014-10-30T06:01:01**-06:00** , it should be 2014-10-30T01:01:01**-08:00** the offset value is defaulted to systems time zone which is central time.

    DateTime inputtime;
    string TimezoneID;
    String outputdateformat;
inputtime = "2014-10-30T08:01:01-05:00"
TimezoneID ="Pacific Standard Time".
Outputdateformat ="yyyy-MM-ddThh:mm:ss zz"

DateTime finaloutputtime = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(inputtime,TimezoneID);

string FinalFormattedDate =finaloutputtime.toString(outputdateformat);

Upvotes: 3

Views: 1961

Answers (2)

BSG
BSG

Reputation: 1

You can use a dedicated function within TimeZoneInfo if you want to convert a DateTimeOffset into another DateTimeOffset

DateTimeOffset newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

or you can do like this

DateTime utc = new DateTime(2014, 6, 4, 12, 34, 0);


TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard   Time");

// it's a simple one-liner
DateTime pacific = TimeZoneInfo.ConvertTimeFromUtc(utc, tzi);

Upvotes: 0

DrewJordan
DrewJordan

Reputation: 5314

You can use DateTimeOffset instead of DateTime to handle this:

            DateTimeOffset time = DateTime.Now;
            string timezoneID = "Pacific Standard Time";
            TimeZoneInfo info = TimeZoneInfo.FindSystemTimeZoneById(timezoneID);

            DateTimeOffset newTIme = TimeZoneInfo.ConvertTime(time, info);


            string timeformat = newTIme.ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");
            string oldtimeformat = time.ToString("yyyy-MM-dd HH:mm:ss \"GMT\"zzz");

Upvotes: 1

Related Questions