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.
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 have a backend written on top of node.js, I'm using TypeORM as the ORM and Azure SQL Database to store my data. When I call the ORM's create() and save() functions, I'm passing in the correct date and time as can be seen below. But when I query the inserted data in the server, the timezone has shifted from -03:00 to +00:00. It maybe a normal behavior, since I'm new working with dates though.
This is the code where I call the create() in:
class CreateAppointmentsService {
public async execute({ provider, date }: RequestDTO): Promise<Appointment> {
const appointmentsRepository = getCustomRepository(AppointmentsRepository);
const roundDate = startOfHour(date);
const foundAppointment = await appointmentsRepository.findByDate(roundDate);
if (foundAppointment) {
throw Error('This date and time already has a booking.');
}
const appointment = appointmentsRepository.create({
provider,
date: roundDate,
});
await appointmentsRepository.save(appointment);
return appointment;
}
}
This is my debug information, showing date and time in expected timezone.
This is the data in the database. The field type is datetimeoffset and the server time is set to UTC (+00:00).
Thanks in advance! =)
[EDIT]: Explaining better: the time I posted to the database is rounded to 20:00 -03:00 (America/Sao_Paulo/Brasilia). If you look the column "created_at", the time is updated to UTC, but the column "data" only got the timezone set to +00:00, the time remais 20:00.
Found the problem! I forgot to set the "date" column to datetimeoffset in the typeORM model =(.
How it was:
#Column()
date: Date;
Changed to:
#Column('datetimeoffset')
date: Date;
Now it work wonders! The correct timezone is being set alongside the time. Cheers!
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
I have column birthday in postgres with type date, I receive a unixtimestamp from front-end like 716500800. When I am saving it to postgresql, it seems like it is converting based on my local time zone. I don't understand what I should do, here is a code
const date = moment.utc(data.birthday * 1000).format();
console.log(date); // 1992-09-15T00:00:00Z it is right date
db.query(
'UPDATE app_users SET birthday=$1 where id=$2 RETURNING birthday',
[
date,
id
],
(err, bd) => {
console.log(bd.rows); // birthday: 1992-09-14T20:00:00.000Z
}
So I set timezone on server and db to UTC. From front-end I get timezone and chande db field to timestamptz (with time zone). Now I operate with all dates in UTC and show/get from client with time zone.
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.