0

In an input json file i receive dates in this format:

{ "dt_received" : "2016-01-22T12:35:52.123+05" }

When loaded into MongoDB, those dates are stored this way:

dt_received: "2016-01-22T07:35:52.123Z"

The issue is that i need the timezone to calculate my indicator. In constraint, i can't create new columns such as "dt_received_timezone". So i'm looking for changing the date storage format into MongoDB in order to make the timezone appear (or at least not disapear) Is it a way to to this? Or any solution ?

Alex
  • 21,273
  • 10
  • 61
  • 73
Mouette
  • 289
  • 1
  • 6
  • 17
  • if you store the `dt_received` as a real `Date`, you get all of this for free. For example, enter `new ISODate('2016-01-22T07:35:52.123Z').getTimezoneOffset()` in your mongo-shell, you'll get `-60`. Is that what you need? – Rogier Spieker Jan 22 '16 at 09:39
  • This [question](http://stackoverflow.com/questions/10942931) may be of help. – chridam Jan 22 '16 at 09:43
  • That's not what i'm looking for. I would like to retrieve the +05 information, in order to have my original date/hour 12:35:52. – Mouette Jan 22 '16 at 10:15
  • Is there any reason for that? When you render data in Javascript as `new Date('2016-01-22T07:35:52.123Z')` it will show `2016-01-22T12:35:52.123+05`, given the browser's timezone is +5. – Alex Blex Jan 22 '16 at 10:57

1 Answers1

0

If you receive data from various time zones and want to keep the time zone offset, you will have to save it into the database like this:

var now = new Date();
db.data.save( { date: now, offset: now.getTimezoneOffset() } );

You can then reconstruct the original time like this

var record = db.data.findOne();
var localNow = new Date( record.date.getTime() -  ( record.offset * 60000 ) );

See the documentation for further details

Alex
  • 21,273
  • 10
  • 61
  • 73
  • 3
    It works with assumption that application server's (mongo client's) timezone is +5, which may not the case. Original timezone is not persisted anywhere and will be lost unless explicitly saved to a separate property of the document. – Alex Blex Jan 22 '16 at 11:51
  • Yes, you are correct @AlexBlex. I have updated my answer. Of course, the recommended way is store the time offset in a field, however, the Rouse doesn't seem to be allowed to do that. – Alex Jan 22 '16 at 12:29
  • @Jaco: this operation returns -1 which this offsets of my mongo server. I could received data from various timezones and I need to keep this information. – Mouette Jan 22 '16 at 14:01
  • If you really need to keep the time zone information (rather than UTC dates across the board), you will have to save it. I have updated my answer – Alex Jan 22 '16 at 14:06