The user enters the date and time in separate text fields. Then I combine the date and time into the date and time. I need to convert this datetime to UTC in order to store it in the database. I have a user timezone identifier stored in the database (they select it during registration). First, I tried the following:
string userTimeZoneID = "sometimezone"; // Retrieved from database
TimeZoneInfo userTimeZone = TimeZoneInfo.FindSystemTimeZoneById(userTimeZoneID);
DateTime dateOnly = someDate;
DateTime timeOnly = someTime;
DateTime combinedDateTime = dateOnly.Add(timeOnly.TimeOfDay);
DateTime convertedTime = TimeZoneInfo.ConvertTimeToUtc(combinedDateTime, userTimeZone);
This led to an exception:
The conversion could not be completed because the supplied DateTime did not have the Kind property set correctly. For example, when the Kind property is DateTimeKind.Local, the source time zone must be TimeZoneInfo.Local
Then I tried to set the Kind property like this:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Local);
This did not work, so I tried:
DateTime.SpecifyKind(combinedDateTime, DateTimeKind.Unspecified);
That didn't work either. Can someone explain what I need to do? Am I even right about this? Should I use DateTimeOffset?
source
share