I am using Date.now() to get the current date and time, but I didn't know the problem I am having. The scenario is this that I use console to check whether date.now() generating correct time or not? Unfortunately I got the correct date in Unix code value convert and check that was correct time and date but when I put that in mongoo schema it used few hours back and store date with few hours back time. But when I get that object with date it returns me the few hours back date and time but when I bind that with Angular front it shows me the correct time the time I put on mongoo the problem is I am not able to filter data by date bcs that object contain few hours back time.
Here is the typescript object that I am pushing on the mongoo
bill = {
orderArray: [],
//investment total
totalActual:0,
//sale total
totalSale: 0,
//investment - sale
totalSave: 0,
quantity: 0,
date: Date.now()
}
and here is the mongo schema:
var cartSchema = mongoose.Schema({
orderArray: Array,
date: { type: Date, default: Date.now },
totalActual: Number,
totalSale: Number,
totalSave: Number,
})
Please check to whether your DB server and application running in the same timezone
Or convert your local time to UTC format from application side and pass it MongoDB
Related
I am trying to store default date and time using mongoose with the Node.JS but somehow, it is storing different time zone value in database. I'm using "MongoDB Atlas Database" as a DB server and also configured default time zone with reference to this. I have also tried this for change time zone and also tried "moment-timezone.js", But didn't get any luck.
I just want to store default date and time with Indian standard time format.
Following is my code for the schema.
const testSchema = new mongoose.Schema({
from: String,
to: String,
amount: Number,
message: {
type: String,
default: ""
},
creationdate: {
type: Date,
default: Date.now
}
});
Please help me with this issue. Show me the best way to solve this problem.
MongoDB stores Date fields as a UTC timestamp in milliseconds since the Unix epoch, which is a 64bit integer (53bit in JS). This is also what Date.now() is. There is no timezone component to the data by design.
If you need a consistent timezone format for a Date object, add a virtual field that returns the required timezone adjusted string or object from the date.
const testSchema = new mongoose.Schema({
creationdate: {
type: Date,
default: Date.now
}
});
testSchema.virtual('formattedCreationDate').get(function() {
return this.creationdate.toLocaleString(); // or day.js/luxon
});
If you need a timezone other than the user or system supplied value, store the required TZ data in another field and use that timezone field in the virtual formatting.
The virtual will probably be easier if you use day.js or luxon.
I am new to PostgreSQL and using it for the first time with Sequelize package in NodeJS.
My Local timezone: IST (+05:30)
Sequelize timezone: UTC (+00:00)
Model
SomeModel = psql.define('SomeModel', {
month: {
type: Sequelize.DATE,
field: 'month'
},
uploadedDate: {
type: Sequelize.DATE,
field: 'uploaded_date'
},
name: {
type: Sequelize.STRING,
field: 'name'
}
}, {
tableName: 'some_table'
});
Input data
month: 'Dec-2017'
uploadedDate: '11-Dec-2017'
Saved Data
month: '2017-11-30'
uploadedDate: '2017-12-10 02:00:00'
I understand the month field UTC conversion sends it 5 hours 30 mins back in time so its November again but following this uploadedDate should be '2017-12-10 18:30:00'.
Why do PostgresSQL takes it to 02:00, what happened at 02:00?
Now one more weird thing I don't understand, when I try to fetch this same row values are changed again.
Output Value
month: '2017-11-30'
uploadedDate: '2017-12-09T20:30:00.000Z'
Now why does it converts already converted time again into UTC, just to increase my problems.
Please help what I am missing and how I can fix this.
After searching for few days I corrected it by doing following and understood the whole scenario.
Column was not storing timezone (but it was not required in my case)
Query was being fired 4 times which makes the date go to 2AM i.e. 5:30*4=22 which makes sense now
Node was taking my server's localtime zone and converting it to UTC each time query fires.
The solution was converting the timezone of my server to UTC and everything worked like charm without any modification in the code.
I've run into problem. I made field in my Mongoose schema with type "Date":
...
timeOfPassingQuestion: Date,
...
Now, I want to pass current time in hours, minutes, seconds and miliseconds and save it into that field. How should I format my Node variable so I can pass it without errors?
Edit: Also, I forgot to say that I wanna later see how much time user spent answering question by subtracting current time and time that I pulled from DB, timeOfPassingQuestion field.
This is the syntax to create a schema that supports a date field:
// Schema
{ //...
someDate: Date,
}
// date object that you can use whenever you decide to set it
var dateObj = new Date();
This will create a JavaScript date object that you can then pass into your Mongoose object for the date field.
Or, if you will always want it on creation, put it directly in your mongoose schema
{ //...
createdDate: { type: Date, default: Date.now },
}
In order to compare the time in the future, I suggest you use moment.js, then you can query the time difference like so:
moment(Model.createdDate).fromNow();
Sources:
Mongoose Schema
Moment.js fromNow
I'm using mongoose models to save my records including created and updated dates. Here's my model schema:
var CasesModelSchema = new mongoose.Schema(
{
caseId: Number,
sessionId: String,
createdAt: {type: Date},
updatedAt: {type: Date, default: Date.now},
docs: mongoose.Schema.Types.Mixed
},
{
collection: 'cases'
}
);
The problem I'm facing is that the updatedAt field saves the datetime as ISODate("2017-04-24T12:40:48.193Z"), which is in UTC, but my server's timezone is Asia/Calcutta. Since I need to make queries according to my server's time, I need the datetimes to be saved in my preferred timezone.
Here's the query I need to execute (get all data for the last 10 days)
var today = moment(moment().format('YYYY-MM-DD')).toDate();
var tenDaysDate = moment(moment().format('YYYY-MM-DD')).add(-10, 'days').toDate();
CasesModel.findOne({updatedAt: {$gte: tenDaysDate, $lt: today}},
function(err, caseData){
cl(caseData, __line);
});
What I want is to do a query to get all the updated records in the last 10 days, exactly from 10 days ago midnight (Asia/Calcutta timezone) to today's midnight (Asia/Calcutta timezone). How do I do that?
What I want is to do a query to get all the updated records in the last 10 days, exactly from 10 days ago midnight (Asia/Calcutta timezone) to today's midnight (Asia/Calcutta timezone). How do I do that?
If by "today's midnight" you mean the last midnight that happened (in which case you will not get results from a moment ago), then you can use something like this - using your local time zone:
// use moment-timezone to handle time zones correctly:
const moment = require('moment-timezone');
let end = moment().startOf('day').tz('UTC')
let start = end.subtract(10, 'days');
or explicitly using Asia/Calcutta time zone:
let end = moment.tz('Asia/Calcutta').startOf('day').tz('UTC');
let start = end.subtract(10, 'days');
If by "today's midnight" you mean the next midnight that will happen (in which case you will get results from a moment ago), then you can use something like this - using your local time zone:
let end = moment().endOf('day').tz('UTC')
let start = end.subtract(10, 'days');
or explicitly using Asia/Calcutta time zone:
let end = moment.tz('Asia/Calcutta').endOf('day').tz('UTC');
let start = end.subtract(10, 'days');
You will have UTC dates that correspond to your local midnights, ready to use in Mongo queries.
No need to change anything in Mongo.
I'm trying to use MomentJS to get non-localized UTC time and set that as the default for new documents created in Mongo.
var SubFavoriteSchema = new Schema({
user : { type: String, ref: 'Account'},
date : {type: Date, default: moment.utc()}
});
The problem is, moment.utc() returns the date that the Node server started. Thus if I start the server on Jan 1, all the documents get a UTC time of Jan 1, even if the document is created on Jan 10.
Any idea why it keeps getting the server's start time instead of the current time?
The problem is that you're calling the moment.utc() function (once) when creating the schema, so the same resulting value is used when creating new documents.
However, you don't need to use moment for this, default: Date.now will do what you want as that function returns the current UTC time. Note that you don't call the now function, you just pass the function itself. That's the key difference.
You need to use a factory function for that.
var currDate(){
return function(){
return moment.utc();
}
}
var SubFavoriteSchema = new Schema({
user : { type: String, ref: 'Account'},
date : {type: Date, default: currDate()}
});