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);
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");