I am attempting to print (to screen) a datetimeoffset in a user-defined time zone. However, it seems that the "TimeZoneInfo.ConvertTimeFromUtc" function actually changes the time object, and the "ToString" function always reverts to the system time zone. Here is my code:
var myDate = DateTimeOffset.Parse("2023-08-18T12:39:00.000-0800"); // date input as PST
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Greenwich Standard Time");
DateTime printableTime = TimeZoneInfo.ConvertTimeFromUtc(myDate.UtcDateTime, tzi); // converting to UDT per customer's request
logger.LogInformation(printableTime.ToString("yyyy-MM-dd HH:mm:sszzz")); // (attempt to) output in UDT
It actually changes the time, and then prints that time in CST (my system time zone):
2023-08-18 20:39:00-05:00
Am I not understanding how TimeZoneInfo.ConvertTimeFromUtc
works? I thought it just changed the time zone of the DateTime object. What am I missing here? What do I need to do to make the "ToString" function simply print the original DateTime object in the "Greenwich Standard Time" time zone, like this:
2023-08-18 20:39:00+00:00
*Edit: I cannot simply use model.DateFrom.UtcDateTime
to get the UDT date, as this is customer defined. They selected UDT in this example, but they may also select something else, such as "Eastern Standard Time" or "Myanmar Standard Time", etc.
You can try using TimeZoneInfo.ConvertTime
:
Converts a time to the time in a particular time zone.
DateTimeOffset printableTime = TimeZoneInfo.ConvertTime(myDate, tzi);
Console.WriteLine(printableTime.ToString("yyyy-MM-dd HH:mm:sszzz"));