Comparing two date values in cypress - javascript

I'm trying to check if one date value that I get from the element in the app is less than today's date:
const todaysDate = Cypress.moment().format('DD/MM/YYYY')
it("Check date to be less or equal than todays", () => {
cy.get('.date', { timeout: 15000 }).eq(3).invoke('text').should('be.lte', todaysDate);
})
However I'm getting the following error:
Timed out retrying after 4000ms: expected '12/14/2020' to be a number or a date
Is there a way to convert the date I get from element to a datetime object?

You can use what JavaScript has to offer:
const date = new Date('12/14/2020');
so in the context of Cypress:
it("Check date to be less or equal than today", () => {
cy
.get('.date', { timeout: 15000 })
.invoke('text')
.then(dateText => {
const date = new Date(dateText);
const today = new Date();
expect(date).to.be.lte(today);
});
});

The moment library is deprecated, using dayjs is recommended instead. You'll need this when parsing custom date formats, which might not be supported by the Javascript Date constructor. Based upon your error message I assume the expected format should be MM/DD/YYYY instead of DD/MM/YYY.
it("Check date to be less or equal than todays", () => {
cy.get('.date', { timeout: 15000 }).invoke('text').then(actualDateText => {
const dayjs = require('dayjs');
const todaysDate = new Date();
const actualDate = dayjs(actualDateText, 'MM/DD/YYYY').toDate();
expect(actualDate).to.be.lte(todaysDate);
});
});

Related

Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'

I want to compare last 30 mins data and display in UI. Datetime needs be UTC. I tried using Moment but i am getting error
Javascript - Operator '>' cannot be applied to types 'Date' and 'Moment'.
Below is my code :
let d = moment();
let d_utc = moment.utc();
var customDate = new Date();
d_utc.minutes(-30);
filteredData = filteredData.filter((category) => {
return category.uploaded_time > d_utc;
});
If you wish to compare a Date to an instance of a Moment with a Date, you need to convert them both to the same date.
You can call .toDate() to convert a moment to a Date or moment(date) to convert a Date to a Moment.
return category.uploaded_time > d_utc.toDate()
JavaScript doesn't have operator overrides, so the safest way to compare Moments is using diff:
return moment(category.uploaded_time).diff(d_utc) > 0
At the documentation in get+set section you can compare the seconds
Examplet in documentation
moment.utc().seconds(30).valueOf() === new Date().setUTCSeconds(30);
Your code should be
let d_utc = moment.utc();
let d_utc = moment.utc().minutes(-30).valueOf();
filteredData = filteredData.filter((category) => {
return category.uploaded_time.getUTCSeconds() > d_utc;
});
Also there is a query section you can check it

Use date-fns to format day as UTC

I have the following date format 2022-07-20 and I would like to parse into the following format 2022-07-20T00:00:00.000Z
I'm using the following code
const main = () => {
const day = '2022-07-20'
const date = new Date()
const result = parse(day.toString(), 'yyyy-MM-dd', date)
console.log(result.toISOString())
}
And getting the following output 2022-07-19T21:00:00.000Z. I assume this happening because my timezone is UTC+3.
How do I get it formatted as 2022-07-20T00:00:00.000Z?

Compare two dates in cypress

How can I compare two dates in Cypress without them beeing modified?
let today = new Date();
let dateDisplayed = "22.07.2022".split('.');
let dateToCompare = new Date(
+dateDisplayed[2],
+dateDisplayed[1] - 1,
+dateDisplayed[0]
);
let firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
expect(dateToCompare).greaterThan(firstDayOfMonth);
When I run the tests I get the following output.
Does the 'expect' function modify my date values? It seems that both values are decreased by one day. How do I overcome this problem?
Thanks for your help!
They aren't modified as much as translated from your time zone (Central European Summer Time, is it?) to GMT. Your midnight is 10pm in Greenwich.
Considering that it happened to both dates, it doesn't change the result of the comparison.
If it nevertheless bothers you, there's Cypress' clock function to influence how it handles, among other things, Date objects.
https://docs.cypress.io/api/commands/clock
You can use day.js library for this. For assertion, you can apply the isAfter to compare both the dates like below:
const dayjs = require('dayjs')
describe('test suite', () => {
it('Test', () => {
let dateDisplayed = '22.07.2022'.split('.')
let dateToCompare =
dateDisplayed[2] +
'-' +
(+dateDisplayed[1] - 1).toString() +
'-' +
dateDisplayed[0]
let firstDayOfMonth = dayjs().startOf('month') //2022-07-01T00:00:00+03:00
const result = firstDayOfMonth.isAfter(dayjs(dateToCompare))
cy.then(() => {
expect(result).to.eq(true)
})
})
})

Mongoose lte method not working for moment

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) } });

exact string match is not returning true in JavaScript filter helper

I'm using a filter helper to create a new array of items that match today's date. I've confirmed that the two comparisons are both a string with a length of 10, yet they're not being recognized as a match when compared in a filter.
I know it has to do with the new Date() method because the first comparison works when I test it against a string of the date while the new Date method does not.
if(chosenDate === 'today') {
// this does not work even though both values are equal
const scheduled = this.props.scheduled.filter(event => event.scheduled_at.substring(0, 10) === new Date(), 'yyyy-MM-dd');
// this works
const scheduled = this.props.scheduled.filter(event => event.scheduled_at.substring(0, 10) === '2019-11-14');
// this does not work
const scheduled = this.props.scheduled.filter(event => '2019-11-14' === new Date(), 'yyyy-MM-dd');
console.log(scheduled)
}
console.log(this.props.scheduled[0].scheduled_at.substring(0, 10));
console.log(dateFnsFormat(new Date(), 'yyyy-MM-dd'));
Why is new dates string not comparing equally?
It seems like you meant
const scheduled = this.props.scheduled.filter(event =>
event.scheduled_at.substring(0, 10) === dateFnsFormat(new Date(), 'yyyy-MM-dd')
);
but wrote
const scheduled = this.props.scheduled.filter(event =>
event.scheduled_at.substring(0, 10) === new Date()
, 'yyyy-MM-dd'
);

Categories

Resources