PostgreSQL with Sequelize acting weird with Timestamps - node.js

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.

Related

Typeorm converting date to +3 hours?

I trying get the real hour of a register as do in my postgresSQL, when I access the DB I see
DB Register with Date Today, 11:30
When I do my request
const tomorrow = moment().add(1, 'days');
const today = moment().startOf('day');
return this.ormRepository.find({
where: {
startHour: MoreThanOrEqual(today),
endHour: LessThanOrEqual(tomorrow),
},
order: { startHour: 'ASC' },
join: {
alias: 'reserves',
leftJoinAndSelect: {
table: 'reserves.table',
},
},
});
}
with typeorm to view the postgres register I see a different hour Today, 14:30.
Today 14:30 Sample
I don't know whats happening and can't found it in any documentation, in production its all ok, the problem is in my dev and I can't found any solution.
I tested my code in a docker container and the date is coming right (Today, 11:30)
Update: I temporaly solved the problem changing my computer time to UTC
What type of field in postgres you setup ? timestamptz ?
In postgres if you execute select Date() you received UTC

Store wrong timezone in default date and time

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.

How to move the time using UTC in sequelize

I am using sequelize and want to get depends on the date.
So when I write the code below, It works well.
But the problem is that since this is the UTC, the local time is different. I need to move UTC time.
For example, "2019-08-21T00:00:00.000Z - 04:00:00".
How can I make this condition ?
Thank you so much for reading.
const total = await models.parcel.findAll({
where: {
createdAt: {
[Op.between]: ['2019-08-21T00:00:00.000Z', '2019-08-21T23:59:59.999Z'],
},
},
});

how to fix the date error using Date.now()

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

Sequelize went wrong when saved date in nodejs

I tried to store an object to Mysql with Sequelize, Nodejs. Every things did ok, excepted the timestamp went wrong. There are my lines:
var log = {
id: id,
error_code: error_code,
created_at: moment().format('YYYY-MM-DD HH:mm:ss'),
updated_at: moment().format('YYYY-MM-DD HH:mm:ss')
}
models.ErrorLog.create(log).then(function(log){
console.log('Create Log');
console.log(log);
});
Focus on these two timestamp fields, I have logged and saw it was right when I created it.
var log = {
created_at: '2016-11-16 22:51:24',
updated_at: '2016-11-16 22:51:24'
}
But, It is wrong in the mysql record:
{
created_at: '2016-11-17 05:45:34',
updated_at: '2016-11-17 05:45:34'
}
In MySql, these fields are defined as:
- created_at: timestamp, nullable
- updated_at: timestamp, nullable
It is very basic, so I don't know what happened. It's so strange!
Where is my mistake?
Use the Sequelize options.timezone property when creating your database connection to make sure that the application and MySQL server are both set to the same timezone offset.
[options.timezone='+00:00']
String
The timezone used when converting a date from the database into a JavaScript date. The timezone is also used to SET TIMEZONE when connecting to the server, to ensure that the result of NOW, CURRENT_TIMESTAMP and other time related functions have in the right timezone. For best cross platform performance use the format +/-HH:MM. Will also accept string versions of timezones used by moment.js (e.g. 'America/Los_Angeles'); this is useful to capture daylight savings time changes.

Resources