Fetch record using Date Sequelize - javascript

How to fetch all records within the same day using deliveryDate as parameter.
For example when passing 2023-02-13T12.23.00 as a parameter, I should get records that fall within that same day i.e 2023-02-13T09.23.00, 2023-02-13T16.01.00, regardless of the timestamps using Sequelize.
Here is the query I am using:
const result = await Order.findOne({
where: {
leaderId: leaderId,
deliveryDate: deliveryDate
}
});

You should use the the sequelize query operators combining a lower and higher Date ranges:
let deliveryDate; // some `deliveryDate` being a Date object (make sure to format it properly and have the desired timezone)
cont low = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const high = low = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59, 999);
const result = await Order.findOne({
where: {
[Op.and] : [
{
leaderId: leaderId
},
{
deliveryDate: {
[Op.lt]: high,
[Op.gt]: low
}
}
]
}
});

Related

There is no calibration between MongoDB UTC time and local time

Data is stored and inquired through the API on the web page, and the API is using MongoDB.
The server space has been unified to UTC time so that the same results can be achieved in different time zones.
MongoDB uses the Mongoose schema as follows:
const userSchema = new Schema({
userId : {
type : String
},
score : {
type : Number
},
createdAt : {
type : Date,
default : Date.now
}
});
Because Date.now in the schema is in the createdAt field by default, it does not pass the Date value separately when querying the create or update of mongoose.
Considering the case where offset exists based on UTC time, the time is calculated using moment.js as follows:
// -540 offset value for KST 9 hours faster than UTC
const utc= moment.utc().add(offset, 'm').format('YYYY-MM-DDTHH:mm:ssZ');
let beginDate = new Date(utc);
let endDate = null;
let year = beginDate.getFullYear();
let month = beginDate.getMonth();
let date = beginDate.getDate();
// To view the full duration of the day
beginDate = new Date(new Date(year, month, date).setHours(0, 0, 0, 0));
endDate = new Date(new Date(year, month, date).setHours(23, 59, 59, 59));
// Find document
const user = await userSchema.aggregate([
{
$unwind : 'lists'
},
{
$match : {
'lists.createdAt' : {
$gte : beginDate,
$lte : endDate
}
}
},
...
]);
For example, if you make a query in Korea, the data inquiry may differ from the time after midnight and to 9 a.m. the next day.
What is wrong with the above parallax correction logic? I don't exactly understand the current problem.
Why so difficult? Simply use
{
$match : {
'lists.createdAt' : {
$gte : moment().startOf('day').toDate(),
$ltr : moment().endOf('day').toDate()
}
}
}
moment().startOf('day').toDate() returns the begin of current day in your local time zone. I live in Switzerland, thus it returns ISODate("2023-01-17T23:00:00.000Z")
But you can specify also a time zone, e.g.
moment.tz('Asia/Seoul').startOf('day').toDate();
ISODate("2023-01-17T15:00:00.000Z")
The problem is moment.utc().add(...) really modifies the time value. But that is not what you need to do, you like to change only the way how the time is displayed in your local time zone.
For comparison and calculations, the displayed value does not matter. All methods are done in UTC time only.

How can I query where it will only show the documents where it has a field timestamp of today's date?

i have these two "where" and if I'll add the "where" for the date, it's not working anymore. I just watn to show all of the orders with the order status of confirmed and a delivery date of today.
var start = new Date();
start.setUTCHours(0, 0, 0, 0);
var startOfDay = start.toLocaleDateString();
console.log(startOfDay);
var end = new Date();
end.setHours(23, 59, 59, 999);
var endOfDay = end.toUTCString();
console.log(endOfDay);
try {
firestore
.collection("orders")
.where("orderStatus", "==", "Confirmed")
.where("deliveryDate", ">=", startOfDay)
.where("deliveryDate", "<=", endOfDay)
.onSnapshot((snapshot) => {
const orders = [];
snapshot.docs.map((doc) => {
const data = doc.data();
orders.push({
"Order ID": doc.id,
});
});
console.log(orders);
this.setState({ orders: orders });
console.log(this.state.orders);
});
} catch (err) {
console.log(err);
}
}
This is the timestamp field in firestore
To get the messages matching a given year, month or day you will have to
Store the year, month and day as separate fields in your document
Change your query (example to query for the day)
firestore
.collection("orders")
.where("orderStatus", "==", "Confirmed")
.where("day", "==", Math.floor(Date.now()/(1000*3600*24)))
.get()
A JavaScript Date object contains more information. According to its docs:
JavaScript Date objects represent a single moment in time in a platform-independent format. Date objects contain a Number that represents milliseconds since 1 January 1970 UTC.
So when you call new Date() is represents that exact moment in time, and it is very unlikely that your database contains a document with that exact same timestamp.
That's why you'll usually want to query on a date range on timestamp fields. So you'll determine the exact dates for the start of the day, and the end of the day, and then do:
firestore
.collection("orders")
.where("orderStatus", "==", "Confirmed")
.where("date", ">=", startOfDay)
.where("date", "<=", endOfDay)
Also see:
Query specific day in Firestore
Cloud Firestore: Storing and querying for today's date over multiple UTC offsets?
Results for searching javascript to determine date for start and end of day
I have already fixed this and this is the updated code by converting the javascript startofDay and endofday to firebase timestamp.
var start = new Date();
start.setUTCHours(0, 0, 0, 0);
var startOfDay = start.toLocaleDateString();
var end = new Date();
end.setHours(23, 59, 59, 999);
var endOfDay = end.toUTCString();
var myTimestamp = firebase.firestore.Timestamp.fromDate(
new Date(startOfDay)
);
var ending = firebase.firestore.Timestamp.fromDate(new
Date(endOfDay));
console.log("end", ending);
try {
firestore
.collection("orders")
.where("orderStatus", "==", "Confirmed")
.where("deliveryDate", ">=", myTimestamp)
.where("deliveryDate", "<=", ending)

How to use intervalToDuration function from date-fns

I tried using the intervalToDuration function from date-fns but I keep getting an error that says End Date is invalid.
My code is as follows
import { intervalToDuration} from "date-fns";
remaining() {
const now = new Date();
const end = this.endDate;
return intervalToDuration({
start: now,
end: end,
});
},
this.endDate is dynamically populated but for this question is equal to 2021-02-26T00:00:00.000Z
Since your endDate variable is coming from an API, it is being stored as a string, not a date.
Calling intervalToDuration is expecting an interval object to be passed as the parameter. An interval consists of two Dates or Numbers (unix timestamp)
To correct this, you must convert endDate to a date object, below is an untested example;
const remaining = () => {
const endDate = "2021-02-26T00:00:00.000Z";
const now = new Date();
const end = new Date(endDate);
return intervalToDuration({
start: now,
end: end
});
};
const dur = remaining();
console.log("DURRATON ", JSON.stringify(dur));
//
// Response == DURRATON {"years":0,"months":1,"days":8,"hours":15,"minutes":42,"seconds":0}
//
Notice : This does not handle timezones correctly. new Date() will create a datetime in the client timezone where it appears that your response from the API is in GMT timezone

How to parse timestamp to JSON in NodeJS?

I wanna create a NodeJS application with an API which provides a current timestamp in JSON-format. This JSON should be called when the user calls the /api/current_time path.
The format could be look like this:
{
"date" : 24,
"month": 12,
"year" : 2020,
"hours" : 10,
"minutes" : 10,
"seconds" : 54
}
I would work with Date-Object. How can I parse these variables into a new JSON-File? The values should be refreshing when the user presses F5.
How can I realize this?
Thanks.
If I understood you correctly, you need to return a JSON when the /api/current_time path gets called. I suppose you mean JSON object instead of "JSON-File". If so, something as simple as:
const date = new Date();
const dateRepresentation = {
year: date.getUTCFullYear(),
month: date.getUTCMonth() + 1,
day: date.getUTCDate(),
hours: date.getUTCHours(),
minutes: date.getUTCMinutes(),
seconds: date.getUTCSeconds()
};
return JSON.stringify(dateRepresentation); // or simply - return dateRepresentation;
The returned date will be in UTC.
You Can also use moment.
I am reusing zhulien example with moment :
const currentDate = moment(); //get the current Timestamp.
return dateObject = {
seconds = currentDate.format('ss'),
minutes = currentDate.format('mm'),
hours = currentDate.format('hh'),
year = currentDate.format('YYYY'),
month = currentDate.format('MM'),
day = currentDate.format('DD')
};

Query by date with column that is a datetime

How can I query for all records of a certain date if the column is a datetime?
This doesn't work. Is there a preferred way to do this in sequelize?
startDate and endDate are datetime's
Thing.findAll({
where: {
startDate = {
[Op.gte]: '02-20-2020'
},
endDate = {
[Op.lte]: '02-20-2020'
},
}
});
Split them and create a javascript Date object before using that straight in the query parameters.
const [month, day, year] = '02-20-2020'.split('-')
const date = new Date(year, month, day)
Thing.findAll({
where: {
startDate = {
[Op.gte]: date
}
}
});
See Several ways to create a Date object

Categories