How to move the time using UTC in sequelize - node.js

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'],
},
},
});

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

Node.js with TypeORM inserts wrong timezones into Azure SQL Database

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!

How to trigger a function on a certain time using timestamps from mongodb?

Let's say i am storing some timestamps in my MongoDB, each timestamp indicates a time when some certain function should be run.
I am not sure what should be the correct approach to this since I am new in backend developing.
Mongo data structure goes like this(this is just an example):
{id: 115155, userId: 152115, timestamp: 13-09-2019:15:30:00}
and on this certain time I want to trigger a function:
someFunction(eventId, userId){ ...something here }
You need to change the format of timestamp you get from mongodb into something like this - "13 Sept 2019 18:39:40" or "2019-01-01 00:00:00". Then you need to parse the timestamp you get from mongodb using this Date.parse()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Once that is done you need to get difference between timestamp and current time and use that difference in a setTimeout() function, which takes 2 parameters - function to be run and time in milliseconds
let timediff = new Date() - Date.parse("2019-09-13 18:54:50");
setTimeout(function() {
console.log("Called when current time = mongodb timestamp");
}, timediff);

PostgreSQL with Sequelize acting weird with Timestamps

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.

Passing current time to Mongoose query

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

Resources