My question is at the bottom of this... but unfortunately, needs a long(ish) explanation:
I'm building a simple app to learn. I have a backend API (written in Hapi) and a mobile app written in Vue NativeScript.
People are to check when a task is completed. A POST request is sent to the API which marks the task as complete and assigns the time completed.
async saveTask(payload, taskType, mongo) {
try {
payload.date = new Date();
await mongo.db.collection(taskType).insertOne(payload);
return {
message: `Data Saved`
};
}
catch (e) {
console.log(e);
throw e;
}
}
As I'm using Mongo - the date is automatically saved as ISODate.
In my mobile app, I have a page that lists all the tasks and when they were completed. A Date picker allows you to view a specific day. Choosing the 10th May, I would see results for 9th May... choosing 9th of May, I would see results for 8th of May etc..
When choosing Friday 10th May 2019 -
My Date Picker returns (console logged) 'Fri May 10 2019 00:00:00 GMT+0100 (BST)'
... When sending this date to the server, the server saw it as 9th May due to the +1 hour British Summer Time and returned results for 9th May.
So, to fix this I converted the date returned from my picker to an ISOString(), and sent this converted date to the server:
query.startDate = this.startDate.toISOString()
returns '2019-05-09T23:00:00.000Z
On the server I log the received query.startDate
and get
startDate: 2019-05-09T23:00:00.000Z
However, in order to get the tasks done for 10th May, I need to set an End Date
To do this, I leaned on Moment.js (is this overkill?)
filters.startDate = moment(query.startDate,'YYYY-MM-DD').startOf('day').toDate();
filters.endDate = moment(query.startDate,'YYYY-MM-DD').endOf('day').toDate();
const query = {
'date' : {
'$gte' : filters.startDate,
'$lt' : filters.endDate
}
};
Moment returns these dates:
{ startDate: 2019-05-09T23:00:00.000Z,
endDate: 2019-05-10T22:59:59.999Z }
Which returns all items from the database with a date of 10th May.
My question is: is this the most efficient / sensible way to handle this. What if an Item is added at 00:00 Hours British Summer Time... (23:00 Hours UTC / GMT)... my endDate doesn't end at 23:00, it ends at 22:59... or am I confusing myself here?
When marking a task as complete, should I be setting the complete time from the local device (I'm thinking not - as new Date is set on the server, this is saved to the Mongo DB in UTC format - and I can use moment or whatever to parse that UTC client side to show the correct date?)
Sorry for the length of this - I'm just extremely confused by dates...