[Solved] [DateTime] Subtract one day, when convert `date` to `string`?


#1

I stay in Cambodia/Khmer and base on Meteor 1.6.

  • My data
{
	"_id" : "001",
	"postDate" : ISODate("2018-03-25T06:00:00.926+07:00"),
	"title" : "Testing",
	"body" : "hello world",
	"status" : "Public",
}
  • Aggregate postDate to String
aggregate([
    {
        $match: {_id:"001"}
    },
    {
        $project: {
            postDate:1,
            dayOfPostDate:{
                $dayOfMonth: "$postDate"
            }
        }
    }
    ])
  • The result
{
	"_id" : "001",
	"postDate" : ISODate("2018-03-25T06:00:00.926+07:00"),
	"dayOfPostDate" : 24
}
  • After that I changed time of postDate >= 07:00:00 AM
    It work fine
{
	"_id" : "001-3",
	"postDate" : ISODate("2018-03-25T07:00:00.926+07:00"),
	"dayOfPostDate" : 25
}

Please help me


#2

I think you might have to do this in app code after data retrieval

Although it looks like Mongo 3.6 (coming soon in Meteor 1.6.2) supports adding a timezone to the $dayOfMonth aggregation:
https://docs.mongodb.com/manual/reference/operator/aggregation/dayOfMonth/index.html

You could try updating to the 1.6.2 beta and adding the timezone to your aggregation:

aggregate([
    {
        $match: {_id:"001"}
    },
    {
        $project: {
            postDate:1,
            dayOfPostDate:{
                $dayOfMonth: { date: "$postDate", timezone: "Cambodia/Khmer" }
            }
        }
    }
    ])

#3

Thanks for your quick reply.
1- Have any solution if we don’t upgrade to Mongo 3.6
2- If we upgrade to Mongo 3.6, the first checking we should do? before upgrade


#4

The safest option that satisfies both 1 and 2 is to just calculate the day of the month inside your app code


#5

Now tried with old version of Mongo

dayOfPostDate: {
                $dayOfMonth: {
                    $add: ["$postDate", 7 * 60 * 60 * 1000]
                }
            }

It work fine.
Please advise


#6

If it now works fine, what is your question?


#7

Thanks again :sunny: