Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB TimeZone

I write into my mongoDB database, for example a startDate, the startdate is always the monday of a week (I use and I'm in middle european timezone).

"startDate" : ISODate("2014-12-28T23:00:00Z"), 
"startDate" : ISODate("2015-03-29T22:00:00Z")
"startDate" : ISODate("2015-04-05T22:00:00Z"), 
"startDate" : ISODate("2015-10-25T23:00:00Z")

I am confused because sometimes the dateformat is:

2014-12-28T23:00:00Z  (sunday, 23h)

and sometimes it is:

2015-04-05T22:00:00Z (sunday, 22h)

In Java- code the date is monday, 00h -> this is ok. Does anyone know whats going on here, why the time is different for the records and how to prevent this?

like image 659
quma Avatar asked Dec 04 '15 09:12

quma


2 Answers

Daylight Saving Time

MongoDB stores dates in UTC by default.

As you are in the Middle European Timezone this means there is either a one or two hour difference depending whether the date falls in or outside the Daylight Saving Time (DST) period. In 2015 DST started on the 29th of March and ended on the 25th of October. Therefore there is a one hour offset for the 28th of December and a 2 hour offset for the 5th of April.

If you want to prevent this, you should convert your local datetime values to UTC times before saving them to MongoDB. Or, as Markus Mahlberg pointed out, convert to local time after loading the date.

like image 89
Alex Avatar answered Nov 15 '22 06:11

Alex


You can convert it to local time.

DateTime startDate = dateFromDb.ToLocalTime();

You could also create a property like this:

DateTime _startDate = DateTime.Now;
public DateTime StartTime { get => _startDate; set => _startDate = value.ToLocalTime(); }
like image 32
Prince Owen Avatar answered Nov 15 '22 06:11

Prince Owen