0

I'm using Mongo's aggregation framework to convert dates to strings using the $dateToString method. It's changing the day though due to the timezone. What can I do to work around this?

Input: new Date("2016-04-19T00:00:00+1000") *Note the time offset changes depending on the item.

Output: "2016-04-18"

Desired Output: "2016-04-19"

Code:

dateString: { $dateToString: { format: "%Y-%m-%d", date: "$date" } }

Strangely using $substring also returns the same result...

dateString: { $substr: ["$date", 0, 10] }
Rob B
  • 1,514
  • 3
  • 23
  • 38
  • 1
    Well `new Date("2016-04-19T00:00:00+1000")` actually is `ISODate("2016-04-18T14:00:00Z")`. BSON Dates are always stored at UTC, and this is a good thing. You probably should be just leaving it alone, but if you must convert to a timezone, then just do the math and add the offset. – Neil Lunn Apr 20 '16 at 06:06
  • @NeilLunn Not really sure this question qualifies as a duplicate... what I'm asking is quite specific and the solution to that question does not fit my needs. My offset times can change depending on the collection item I'm aggregating – Rob B Apr 20 '16 at 06:12
  • 1
    Of course it's a duplicate. As already stated *"all BSON Dates are in UTC"* , which means there is no offset information stored. TImezone is a relative concept to the "client", and clients are in multiple locations. So the only offset that applies is the one coming from the "client's" point of view. You should really be reading the content and understanding it rather than waiting around for a response to say something different. There is no different response. Hence why there is no point opening up to answers that will just say exactly the same thing. – Neil Lunn Apr 20 '16 at 07:14
  • And if you wanted to bring "daylight savings offset into it", ["Aggregate Group by Date with Daylight Saving Offset"](http://stackoverflow.com/questions/36465412/aggregate-group-by-date-with-daylight-saving-offset). So again, it's all relative math and up to the "client" to identify the timezone, and not the server. – Neil Lunn Apr 20 '16 at 07:19
  • How about this way (28800000 is my timezone offset): $dateToString: { format: '%Y-%m-%d %H:%M:%S', date: {$add: ['$time', 28800000]} } – Clement.Xu Apr 06 '17 at 03:39

1 Answers1

0

This happens because it is converting to UTC time.

So either do coding wrt UTC timing or change to ISODate.

Use this link for getting time http://currentmillis.com/

Yatin Goyal
  • 322
  • 3
  • 10