Convert date and time entered by user in UTC

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?

+5
source share
2 answers

DateTime, SpecifyKind - . :

combinedDateTime = DateTime.SpecifyKind(combinedDateTime,
                                        DateTimeKind.Unspecified);

Noda Time, ( ). :

DateTimeZone zone = ...;
LocalDate date = ...;
LocalTime time = ...;
LocalDateTime combined = date + time;
ZonedDateTime zoned = combined.InZoneLeniently(zone);
// You can now get the "Instant", or convert to UTC, or whatever...

"" , , - DST.

+7

var combinedLocalTime = new DateTime((dateOnly + timeOnly.TimeOfDay).Ticks,DateTimeKind.Local);
var utcTime = combinedLocalTime.ToUniversalTime();
+1

All Articles