Ok so this question has been asked here however the solutions given don't seem to resolve my issue.
I have the following:
When I click save I refer to the these fields and create a date as shown here:
this.profile.date_of_birth = new Date(this.editProfileForm.value['year'], this.editProfileForm.value['month'], this.editProfileForm.value['day']);
Which when logged to the console reads:
Fri Dec 23 1988 00:00:00 GMT+1100 (AEDT)
I then make a call to my nodejs application which is running on http://localhost:3005, which takes the data and saves it to mongodb, before the save happens I log the value of date_of_birth as shown here:
api.put('/update', authenticate, (req, res) => {
console.log(req.body.date_of_birth);
// Save properties
});
however this logs:
1988-12-22T13:00:00.000Z
which is a day off....
I'm not doing any formatting before creating a new date when the user presses save, so I'm unsure into why when it leaves the front end application, and gets to the backend application the date is displayed incorrect....
The actual call to the nodejs application is here:
saveProfile(profileId: string, token: string, profile: Profile): Observable<any> {
var body = {
"id": profile.id,
"date_of_birth": profile.date_of_birth,
}
return this.http.put(UPDATE_EDIT_PROFILE, body, {
headers: this.setHeaders(token)
}).map((res: any) => res.json());
}
Can anyone recommend what could possibly going wrong?
Fri Dec 23 1988 00:00:00 GMT+1100 (AEDT) is date with the current timezone. and your server seems using UTC according to 1988-12-22T13:00:00.000Z.
you can use Date.UTC to create a Date Object with standart timezone of UTC which keeps same to your server.
var year = 1988;
var month = 12;
var day = 23;
console.log(new Date(year, month - 1, day));
console.log(new Date(Date.UTC(year, month - 1, day)));
Related
So the problem I'm currently having is :
I've a list of gym classes, which every class has an OpeningTime. I want to fetch all the classes from the current day, but. I'm not getting the same result locally and in production, cause for some reason, when Im deploying my backend to Heroku, the timezone is being setted by default to UTC (when I've a GMT-3 timezone).
Here is my query :
var now = moment();
var startOfDay = now.startOf('day').format();
var endOfDay = now.endOf('day').format();
var clasesDB = await Clase.find({ $and: [{ openingTime: { $gte: startOfDay } }, { openingTime: { $lte: endOfDay } }] })
So, like I said before, the problem is ocurring when, for example:
When I fetch the classes at my local time (Ex: 02-26-19 21:00hs ( GMT-3) ), the queries are actually showing the classes from 02-27, because, at MINE 21:00hs, on the server side is already 00:00, so, the date is not 02-26 anymore. And I dont want this kind of output.
How can I get a workaround to solve this?
Thanks in advance! :)
Don't use .format(), this makes a string. Compare directly Date values, i.e. use
var now = moment();
var startOfDay = now.startOf('day').toDate();
var endOfDay = now.endOf('day').toDate();
By default moment uses local times, so moment().startOf('day') returns midnight of local time. If you want to get midnight of UTC then use moment.utc().startOf('day').
If you don't rely on "local" time zone, then you can specify it like moment.tz("America/New_York").startOf('day')
No matter which time you need, never compare Date values by string, use always actual Date value.
By default in MongoDB a date field is stored in UTC, You can create a date with offset while writing to store it in your timeZone. But you've not done it while writing documents then you need to convert date field to your required timeZone while reading data from database. Check this below example.
JavaScript Code :
const today = new Date().toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric'
}) // 02/26/2020. If your Heroic server is in different location then specify your locale in place of undefined - whereas undefined picks local time by default. Ex:- 'en-Us' for USA
Query :
db.collection.aggregate([
{ $addFields: { timewithOffsetNY: { $dateToString: { format: "%m/%d/%Y", date: "$openingTime", timezone: "America/New_York" } } } },
{ $match: { timewithOffsetNY: today } }, { $project: { timewithOffsetNY: 0 } }
])
Above query is written for New York timeZone, you can convert it according to your timeZone, In test url you can see 1st doc is not returned though it is on 2020-02-26 cause offset to New York as of today is 5hrs, So after converting date becomes as 2020-02-25.
Test : MongoDB-Playground
Ref : $dateToString
Mongoose is saving date-time as ISODate("2017-04-25T09:40:48.193Z")in UTC format. How can i change its time zone to my local server timezone. So i need not to change the time every time i retrieve it from db. Here is my model schema:
var MyModelSchema = new mongoose.Schema(
{
id: Number,
description: String,
created: {type: Date},
modified: {type: Date, default: Date.now},
},
{
collection: 'my'
}
);
PS: I am aware that it is preferred to save time in UTC format but here my requirement is to save it in specified time-zone.
you can save users timezone and while updating add the time zone value to this new object. Better to use moment.js to convert this.
moment
Even thought it is not a good practice to store time in local format but this might help -
date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
changes will be done where you are saving the Object -
var date = new Date(); //2017-04-25T06:23:36.510Z
date.toLocaleTimeString(); //'11:53:36 AM'
var localDate = ""+d; //'Tue Apr 25 2017 11:53:36 GMT+0530 (IST)'
var newModel = new ModelSchema()
newModel.description = 'Something';
newModel.created = locaDate;
newModel.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
I think I have a solution. Try this one for Asia/Calcutta this can be stored as Date type in Mongoose
function getCurrentIndianDateTime(){
var moment = require('moment-timezone');
var time = moment.tz('Asia/Calcutta').format("YYYY-MM-DDTHH:MM:ss");
return new Date(time);
}
I'm writing a React Application that uses MongoDB as its database. There seems to be some strange behaviour when saving and retrieving dates from the database, specifically when updating the date in a particular document.
When I create a new document, everything is fine. However, if I try to edit the date on that document using an ajax call, the date stored in MongoDB is one day earlier than the one I selected and what is displayed in the browser. Code below to explain a little more.
The date is selected using an HTML5 <input type='date' /> element. Here's some of the code. I've included console logs at various points to show the output. Let's assume I'm selecting '30 October 2016' as the date. The date and the year get split up for display purposes elsewhere, but then joined together in the form of a JS Date object before sending to the server (see code below)
React component method:
saveChanges(e, cancel){
e.preventDefault();
const cancelled = cancel ? true : false
console.log(this.state.date); // 30 Oct
console.log(this.state.year); // 2016
const saveData = {
id: this.props.data.id,
venue: this.state.venue,
unitNumber: this.state.unitNumber,
unitName: this.state.unitName,
date: this.state.date,
year: this.state.year,
day: this.state.day,
tutorID: this.state.tutorID,
cancelled: cancelled
}
editWorkshop(saveData, (data) => {
this.props.getWorkshopDetails();
this.props.workshopDetailsSaved(data);
});
}
The above method sends the data to editWorkshop.js, an external ajax call, using axios:
import axios from 'axios';
export default function editWorkshop(input, callback){
const date = new Date(input.date + ' ' + input.year) // Rejoin date and year and convert to Date object
console.log(date); // Sun Oct 30 2016 00:00:00 GMT+0100 (BST)
const data = {
id: input.id,
venue: input.venue,
unitNumber: input.unitNumber,
unitName: input.unitName,
date: date,
day: input.day,
tutorID: input.tutorID,
cancelled: input.cancelled
}
axios.post('/editWorkshop', data).then(function(res){
callback(res.data);
})
}
And finally the express route which handles the ajax call
const express = require('express');
const Workshop = require('../data/models/Workshop');
module.exports = function(req, res){
const data = req.body
console.log(data.date); // 2016-10-29T23:00:00.000Z - here is where it seems to go wrong - notice that the date has changed to 2016-10-29 instead of 10-30. This now gets written to the database
Workshop.update({ _id: data.id }, {
$set: {
unitNumber: data.unitNumber,
date: data.date,
venue: data.venue,
tutor: data.tutorID,
session: data.day,
cancelled: data.cancelled
}
}, function(err){
if (err) {
res.send(err);
return
}
var message = 'Workshop updated'
res.send({
success: true,
message: message
});
})
}
What's really strange is that when I retrieve the data from the database elsewhere in the application, it shows the correct date in the browser - 30 Oct 2016.
Arguably this isn't a problem as the correct date is being displayed, but I'm not comfortable with this as these dates are a fundamental part of the app and I'm concerned that there could be scope for a bug in the future.
Can anyone shed any light on this?
2016-10-29T23:00:00.000Z is same as Sun Oct 30 2016 00:00:00 GMT+0100 (BST).
2016-10-29T23:00:00.000Z is in UTC(GMT) timezone. If you convert that to BST you will get the same value.
MongoDB saves the date values as UTC milliseconds since the Epoch.
From the docs:
MongoDB stores times in UTC by default, and will convert any local
time representations into this form. Applications that must operate or
report on some unmodified local time value may store the time zone
alongside the UTC timestamp, and compute the original local time in
their application logic.
I have been implementing some functions of google calendar api. I have a custom calendar which have the capability to sync with google calendar. This means, you can create, and edit calendars and events from my dashboard to google calendar account. The main problem I am facing is, if I update the event directly from my google calendar. I have implemented push notifications and getting response like this:
{
"Google_channel_ID": "19835150 - 0057 - 11e6 - bc9c - 1735798 ca540",
"Google_channel_token": "calendar_id = 4e7 d5c20ht9lpfdtuukcsvgeq4 #group.calendar.google.com & user_id = 43e d7rxeqqce3fk09ahszc",
"Google_channel_expiration": "Tue,12 Apr 2016 12: 34: 36 GMT",
"Google_resource_id": "oLMEEhHAw5Xo3r2187CWykjAtm0",
"Google_resource_URI": "https: //www.googleapis.com/calendar/v3/calendars/4e7d5c20ht9lpfdtuukcsvgeq4#group.calendar.google.com/events?alt=json",
"Google_resource_state": "sync",
"Google_message_number": "1"
}
But this response is very general. For example, If I have 1000 events on this calendar, and update the complete 1000 events. I will receive always the same notification 1000. I would like to know, if it is possible to get which event id has change, so I can perform and update to my DB.
The way I init the watch is like this:
exports.watch = function(req, res){
var channel_id = uuid.v1();
var user_id = req.body.user_id;
var calendar_id = req.body.calendar_id;
authorize(user_id, function(oauth2Client){
var data = {
auth: oauth2Client,
calendarId: calendar_id,
resource: {
id: channel_id,
token: 'calendar_id='+ calendar_id + '&user_id=' + user_id,
address: 'https://api.medradr.com/google-watch',
type: 'web_hook',
params: {
ttl: '36000'
}
}
};
calendar.events.watch(data, function (err, response) {
if (err) {
console.error('The API returned an error: ' + err);
return;
}else{
res.send({ok: true, message: 'Listener created', result:response});
}
});
});
}
For people who are looking for a good way to get which events changed when the web hook triggers. When your web hook is triggered, you will get something like this:
X-Goog-Channel-ID: channel-ID-value
X-Goog-Channel-Token: channel-token-value
X-Goog-Channel-Expiration: expiration-date-and-time // In human-readable format; present only if channel expires.
X-Goog-Resource-ID: identifier-for-the-watched-resource
X-Goog-Resource-URI: version-specific-URI-of-the-watched-resource
X-Goog-Resource-State: sync
X-Goog-Message-Number: 1
On X-Goog-Resource-URI you will get something like this:
https://www.googleapis.com/calendar/v3/calendars/4e7d5c20ht9lpfdtuukcsvgeq4#group.calendar.google.com/events?alt=json
With you OAuth authentication, you can make a GET request to this URL to fetch all events that belongs to this calendar. Now the trick to know which resources have been changed is really simple. For each event you will get something like this:
{
event_id: 335,
user_id: '43ed7rxeqqce3fk09ahszc',
kind: 'calendar#event',
etag: '"2921213870180000"',
google_id: 'cpbcesg966skprb3rh1p1ud668',
status: 'confirmed',
htmlLink: 'https://www.google.com/calendar/event?eid=Y3BiY2VzZzk2NnNrcHJiM3JoMXAxdWQ2NjggNGU3ZDVjMjBodDlscGZkdHV1a2NzdmdlcTRAZw',
created: Thu Apr 14 2016 00:00:00 GMT-0500 (CDT),
updated: Thu Apr 14 2016 00:00:00 GMT-0500 (CDT),
summary: 'Testing google notifications',
description: '',
creator: 'guizarkrg#gmail.com',
organizer: '4e7d5c20ht9lpfdtuukcsvgeq4#group.calendar.google.com',
start: Sat Apr 09 2016 00:00:00 GMT-0500 (CDT),
end: Sun Apr 10 2016 00:00:00 GMT-0500 (CDT),
iCalUID: 'cpbcesg966skprb3rh1p1ud668#google.com',
event_type_id: 0,
calendar_id: 0,
timezone_id: 0,
sequence: 0,
calendar_color_id: ''
}
As you can see, the is a sequence: 0, this is incremental. This means, each time you apply some changes on your event (summary, description, start date, end date, etc). This number will be incremented +1. You can save this on your database, so each time web hook triggers, you update only events which sequence is > than saved sequence. So basically, you update the event and save the new value of sequence. Next time that web hook triggers, it will only update on your DB the events that are included in this condition.
Hope it helps, happy coding.
I'm new to Node.js and Mongodb so bear with me here.
I have read from multiple places that the best way to store dates is with new Date(). So before I store my dates in the Mongodb I convert them with new Date('10/07/2014'), turning it into 'Tue Oct 07 2014 00:00:00 GMT-0400 (Eastern Daylight Time)'.
The problem is that if I try to run a sort on the collection it sorts them by the day of the week(Mon, Tues, Wed, etc) and not by their actual dates. What am I doing wrong here? Heres some actual code:
//get date from a field and convert it
var date = new Date($('#inputDate').val());
//after storing it in the database I call this line and it sorts it by day of the week.
db.collection('gameslist').find().sort({date:1})
Printing out the sorted collection their dates come out in this order, which is by day of the week and not by actual date.
Fri Feb 20 2015 00:00:00 GMT-0500 (Eastern Standard Time)
Mon Oct 13 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
Sun Feb 15 2015 00:00:00 GMT-0500 (Eastern Standard Time)
Tue Oct 07 2014 00:00:00 GMT-0400 (Eastern Daylight Time)
I've noticed in other posts when people do something like new Date() their dates don't come out like mine but instead come out with less fluff.
EDIT: Adding my actual code.
gamelist.js file that has a function that does an ajax call.
dateCompleted = new Date($('#addgame div input#inputDateCompleted').val());
var newGame = {
'title': $('#addgame div input#inputTitle').val(),
'datecompleted': dateCompleted,
'rating': $('#addgame div select#inputRating').val(),
}
// Use AJAX to post the object to our addgame service
$.ajax({
type: 'POST',
data: newGame,
url: '/games/addgame',
dataType: 'JSON'
})
addgame router at /games/addgame:
/*
* POST to addgame.
*/
router.post('/addgame', function(req, res) {
var db = req.db;
db.collection('gameslist').insert(req.body, function(err, result){
res.send(
(err === null) ? { msg: '' } : { msg: err }
);
});
});