Reputation: 7128
I am working with a MongoDB trying to deserialize a BsonDate
to a DateTime
with the proper Kind
. When a DateTime
is serialized to MongoDB it is saved in UTC format, when it is deserialized it is returned as a UTC format too.
My issue is that I cannot seem to be able to convert the DateTime
I am given back from Mongo to my local DateTime
(UTC to EST). I am pretty sure I can get around my issue by just removing the UTC time offset (AddHours
) for my timezone but I am pretty sure that DateTime
can do this for me and would handle any time zone the application is ran in.
// Deserializing the DateTime object
DateTime eventTimeStamp = (DateTime)aDoc[MongoStrings.Log_Field_TimeStamp];
Console.Out.WriteLine("UtcDate: " + eventTimeStamp);
Console.Out.WriteLine("Locale : " + eventTimeStamp.Kind);
// First attempt at conversion
DateTime localTime = DateTime.SpecifyKind(eventTimeStamp, DateTimeKind.Local);
Console.Out.WriteLine("NewTime: " + localTime);
Console.Out.WriteLine("Locale : " + localTime.Kind);
// Another attempt at conversion
DateTime localTime2 = new DateTime(eventTimeStamp.Ticks, DateTimeKind.Local);
Console.Out.WriteLine("NewTim2: " + localTime2);
Console.Out.WriteLine("Locale : " + localTime2.Kind);
The code above produces the following output
UtcDate: 1/29/2016 2:54:05 PM
Locale : Utc
NewTime: 1/29/2016 2:54:05 PM
Locale : Local
NewTim2: 1/29/2016 2:54:05 PM
Locale : Local
My local time when that log was produced is 9:54:05 AM
.
Upvotes: 0
Views: 3862
Reputation: 4178
This might work for you:
// This is your code
// Deserializing the DateTime object
DateTime eventTimeStamp = (DateTime)aDoc[MongoStrings.Log_Field_TimeStamp];
Console.Out.WriteLine("UtcDate: " + eventTimeStamp);
Console.Out.WriteLine("Locale : " + eventTimeStamp.Kind);
// This is new code
Console.Out.WriteLine("LocalDate: " + eventTimeStamp.ToLocalTime());
The reasoning would be that your localTime variables are set to the exactly same time stamp as the one in UTC, you just say that it should be taken as a local time. But this setting as local time does no conversion of times, it just says what kind of time this is so that other methods (like ToLocalTime) know what to do ...
If you want that local time in a variable, then it might be like this:
DateTime localTime = eventTimeStamp.ToLocalTime();
And I guess it will work without setting the kind. If not, you know how to set the kind ...
Upvotes: 2