let date = "2021-07-31-T18:30:00.000Z"
date = new Date(date)
let nextDate = new Date()
// I have made a addDays function which returns a date.
nextDate = date.addDays(1)
Mongoose query:
$match: {
created: {
$gt: new Date(date),
$lte: new Date(nextDate)
}
}
I want to change the date from "2021-07-31-T18:30:00.000Z" to "2021-07-31-T00:00:00.000Z" so that my query can filter correct data. How can I achieve this?
I tried using setHours but it won't work.
I tried to convert the date string you declared but it kept failing.
I found that the date string you provided in ISO format "2021-07-31-T18:30:00.000Z" is not correct. The correct one should be "2021-07-31T18:30:00.000Z". The hyphen before T should be removed.
Related
I use mongodb as my database and in that db I have a timestamp field but I haven't seen any format similar to that. Some of them are:
1657479170.7300725
1657479170.7301126
1657479170.7301197
1657479170.9120467
1657479170.932398
When i try to convert this to normal date format (YYYY-MM-DD) I get the correct date. For example the converted date of the first timestamp above is:
10.07.2022 21:52:50
However when I try to convert it in javascript I get:
1970-01-20 06:24:39
which is definitely not correct value.
My code for the conversion :
ConvH.forEach(conv => {
conv.tracker.events.forEach(element => {
console.log(parseFloat( parseFloat(element.timestamp.toFixed(4))), moment(new Date( parseFloat( element.timestamp.toFixed(4)))).format("YYYY-MM-DD HH:mm:ss"));
element.timestamp = new Date(element.timestamp).toLocaleString();
})
});
Note : new Date(element.timestamp).toLocaleString(); gives the same thing :/
Try this: new Date(timestamp.getHighBits() * 1000)
I am fetching Date saved in db. Then, I am doing a small date maths to substract date from today from 3, which is giving me Date in Format - (DD-MM-YYYY). Date saved in db format is also same - (DD-MM-YYYY). Can anyone help me out in validating $lte for that date. I am not getting any log for DipData.
nodeCron.schedule("* * * * *", async function () {
var DateNow = await moment().subtract(3, "days").format("DD-MM-YYYY");
console.log("Test Date Cron",DateNow);
console.log("-->",new Date(DateNow.format("DD-MM-YYYY")));
let DipData = await userModel.find({}, { LastAppOpenedTime: { $lte : new Date(DateNow.format("DD-MM-YYYY")) }})
console.log("-----DipData ------->", DipData);
});
First thing you need to identify if there is date which is stored in document of mongo collection is string or regular date format or epoch format. If it's string the query may gives not accurate result. If there is date format or epoch format, you can easily queried your result with proper result.
Therefore in case if there is string in LastAppOpenedTime document key you can have query with $toDate under find query.
If key is not in string format in stored document following code will work.
var DateNow = moment().subtract(3, "days");
const DipData = await userModel.find({ LastAppOpenedTime: { $lte: new Date(DateNow) } });
For the above two scenario would work if your query is in accurate form like removing the first empty braces.
userModel.find({}, { LastAppOpenedTime: { $lte : new Date(DateNow) }})
to
userModel.find({ LastAppOpenedTime: { $lte : new Date(DateNow) }})
Hello I got this working by making a few changes
const DateNow = await moment().subtract(3, "days");
console.log("Test Date Cron", DateNow);
console.log("-->", new Date(DateNow));
const DipData = await userModel.find({ createdAt: { $lte: new Date(DateNow) } });
console.log("-----DipData ------->", DipData);
res.status(200).json({ success: true, message: "Request was successful", DipData });
I noticed you had the .format("DD-MM-YYYY") at the end of your moment function but it returned a string that couldn't be converted with the new Date(DateNow). I removed mine when testing as the response from the moment was working fine without it.
And also I updated your userModel.find({}, { LastAppOpenedTime: { $lte : new Date(DateNow.format("DD-MM-YYYY")) }}) to remove the first empty {}. So you would have userModel.find({ createdAt: { $lte: new Date(DateNow) } });
I have a date in (yyyy-mm-dd) format, i want to get start and end date with timestamps and ISO format, i can concat date and timestamp but i want it in date type not in string,
let date = "2020-09-11";
Expected result should be,
startDate = 2020-09-11T00:00:00.000Z
endDate = 2020-09-11T23:59:59.000Z
The start date is correct, The end date is not correct, it gives different time stamp, 18:29:59.000Z when i set it to setHours(23,59,59),
let startDate = new Date(date);
console.log(startDate);
// output: 2020-09-11T00:00:00.000Z
let endDate = new Date(new Date(date).setHours(23,59,59));
console.log(endDate);
// output: 2020-09-11T18:29:59.000Z
I looked at this question convert string to ISO date time in nodejs, but this does not help me, i don't want to use moment,
Am i doing wrong to convert dates? i am using nodejs.
You should use setUTCHours()
The setUTCHours() method sets the hour for a specified date according to universal time
let date = new Date()
let startDate = new Date(new Date(date).setUTCHours(0,0,0));
let endDate = new Date(new Date(date).setUTCHours(23,59,59));
console.log(startDate);
console.log(endDate);
You could just add the postfix without conversion to a local date.
let date = "2020-09-11",
startDate = date + 'T00:00:00.000Z',
endDate = date + 'T23:59:59.000Z';
console.log(startDate);
console.log(endDate);
I want to validate from and to date. my date format is d/m/Y H:i
Here is my code:
var startDate = new Date($('#fromdate').val());
var endDate = new Date($('#todate').val());
if (endDate.getTime() <= startDate.getTime()) {
return [false,"To Date cannot be less than From Date"];
}else{
return [true,""];
}
result showing 'Invalid Date'.
Here the date format is different. How to change the date format before passing to Date function?.
You can parse the date string on your own or you can use an external library, like dayjs or momentjs
A simple parsing function could be something like this (assuming the format is the one you mentioned in your question):
function getDateFromCustomFormat(dateString) {
const dateFormatPattern = /^([0-9]{2})\/([0-9]{2})\/([0-9]{4}) ([0-9]{2}):([0-9]{2})$/
const parts = dateString.match(dateFormatPattern)
console.log(parts)
const validFormatString = `${parts[3]}-${parts[2]}-${parts[1]} ${parts[4]}:${parts[5]}`
new Date(validFormatString)
}
I am creating a node.js endpoint that accepts a start date/time and end date/time as parameters. I had been passing them as a string ie:
var body = {
relatedObjectId: "561ee6bbe4b0f25b4aead5c8",
startTime : "11/13/2015 03:00:00PM",
endTime: "11/13/2015 03:30:00PM"
};
and in my service class:
var timeTicket = new TimeTicket();
timeTicket.tutorId = tutorId;
timeTicket.startTime = new Date(startTime);
timeTicket.endTime = new Date(endTime);
timeTicket.save(function(err, timeTicket){
if(err){
return next(err, null);
}
return next(null, timeTicket);
});
However, the cast always fails so i end up with a date in 1970 for startTime and endTime values. It would seem the obvious solution would be to use a UTC format, but what's the right way to do that?
Either use ISO 8601 format as Phil suggested, or simply pass the date as milliseconds (since 1970).
For example, new Date(1447378736842) is the same as new Date("2015-11-13T01:38:56.842Z").
To get the current date in ISO 8601 format, you might do something like this:
var d = new Date();
var n = d.toISOString();
tl;dr version: This is what your body object should look like. I used milliseconds for startTime and an ISO 8601 string for endTime for demonstration purposes. Both are valid.
var body = {
relatedObjectId: "561ee6bbe4b0f25b4aead5c8",
startTime : 1447378736842,
endTime: "2015-11-13T01:38:56.842Z"
};