HTML Comparing 2 Dates with Javascript - javascript

I'm trying to compare 2 dates using Javascript. If "myDateL" is after "mydateR" display a message box when the button is clicked.
What is wrong with my code?
I know I've seen a similar thread to this but I couldn't understand it. I hope someone can help me with this please.
<input type="Button" value="TwoDates" onClick="twoDates()">
<script>
function twoDates() {
var firstdate = new date(document.getElementById("mydateL").value);
var seconddate = new date(document.getElementById("mydateR").value);
if(firstdate > seconddate) {
alert('Please change your return date.');
}
}
</script>

It's new Date(...), not new date(...). Date is the global object that holds dates and times, date would be a function you've declared called date. If you look at the console when you run this, you should see something like:
ReferenceError: date is not defined

Related

Cypress API testing - Using custom commands to return a value to avoid duplicating code

First of all. I'm purposely re-learning JS/Cypress and I'm purposely starting from bedrock again, so apologies in advance.
I'm currently using Cypress for REST API testing. I am migrating tests over from an existing Ruby/Selenium framework and I want to use something similar to writing Ruby functions to clean up my code, as I am currently duplicating code.
An example:
I have a block of code that generates a date, 365 days in the past (ISOString used for a reason, in this case)
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
I want to do something like
Cypress.Command.add('dateGen', () => {
var date = new Date();
date.setDate(date.getDate() - 365)
var minDate = date.toISOString().split('T')[0]
})
and call it in. In this case, I would want to call it in to my test using something like
(excuse the incorrect syntax, I'm just doing it as a like for like (Ruby/JS) illustration):
var date = cy.dateGen
However, running this in any js/cypress friendly combination falls over as Commands do not return values.
I am already set up to use commands in index.js etc, so that bit isn't causing me any problems. I am already using commands for things that don't return a value, so I know I'm doing that bit correctly.
I sorted it using the following:
Cypress.Commands.add('dateGenerator', (days) => {
var newDate = new Date();
newDate.setDate(newDate.getDate() - days)
var date = newDate.toISOString().split('T')[0]
return date
})
and then called it via
cy.dateGenerator(noOfDays)
.then((date) => {
var minDate = date
}
The bit I was missing was the
return date and I was closing the blocks off too early in my test code.

is it possible to tweak global Date function?

I'm trying to tweak the global Date function by preserving all functionality of Date but add some parameter checking inside the constructor
because I want to throw an error when calling Date function like this new Date('2021-01-01'), which will return Invalid Date in safari.
(function () {
let OldDate = window.Date;
window.Date = class Date extends (
OldDate
) {
constructor(...args) {
if (/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/.test(args[0])) {
throw Error('wrong date format');
}
super(...args);
}
};
})();
but this approach has a pitfall, I can't call Date without new keyword
// before override
new Date('2021/02/01'); // OK
Date('2021/02/01'); // OK
// after override
new Date('2021/02/01'); // OK
Date('2021/02/01'); // Uncaught TypeError: Class constructor Date cannot be invoked without 'new'
How do I fix it?
the motivation of tweaking the global Date function
most newbies will tend to call Date function with a format like YYYY-MM-DD HH:mm:ss, this works inside his development environment (latest version of Chrome), and he doesn't konw this won't work on safari until he tests his project on safari, so I have to tell him to change the Date format string he uses every time he falls into this problem.
Writing a code style guide won't always work, a newbie is a newbie because he always forgets things, so I have to tell him to read the style guide document again.
Instead, I want to throw an error every time the newbie use Date with the wrong date string format
new Date('2021-01-02') // Error: 'YYYY-MM-DD is wrong format', try use 'YYYY/MM/DD'
No matter why you want to override Date. My solution is
var originalDate = Date; // backup
function _date(str) {
// your implementation here
if (/\d\d\d\d-\d\d-\d\d \d\d:\d\d:\d\d/.test(str)) {
throw Error('wrong date format');
}
return new originalDate(str);
}
window.Date = _date; // override
Object.assign(Date.prototype, originalDate.prototype); // I suppose you still want to have properties of the original Date.

Server-Side and Time-Specific script execution

I have a list of dates in an array(for now we can say that the dates are sorted). I want to have a script execute when the date matches a date in the array. My issue is figuring how to make this work on its own. I would like to have a server somehow act like an alarm clock that can run a script for a scheduled date and time. If anyone could help with suggestions to make this work I would appreciate it.
set date >>> if (currentDate == set date) >>> run script for the respective data
Please ask if you need clarification.
The way to do this with parse is a class with a date attribute. Create one object per date in your array of dates (they needn't be sorted).
Create a scheduled job that upon running, query's the class for the first date equal to the current date. If one is found, do whatever you want to do when an alarm is triggered.
So, something like...
Parse.Cloud.job("checkStatus", function(request, status) {
var today = new Date();
today.setHours(0, 0, 0, 0);
var tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
var query = new Parse.Query("MyAlarmClass");
query.greaterThanOrEqualTo('theDateAttribute', today);
query.lessThan('theDateAttribute', tomorrow);
return query.first().then(function(anAlarm) {
if (anAlarm) {
// do whatever should be done on the alarm
} else {
// do nothing
}
}).then(function() {
status.success();
}, function(error) {
status.error(JSON.stringify(error));
});
});
Schedule this to run at least twice per day (or faster than whatever resolution you need on the alarms).

HTML passing parameters to javascript function that then does a date compare and then javascript returning a result to be displayed in html

I am having problems figuring out how to do a date compare in Javascript, and how to pass and receive varialbes to and from Javascript Function and Html.
I have 4 term dates (workshop start and end dates for each term). I will send one set of dates at a time to the javascript function, and then I want the Javascript to check if today's date falls within the range of that workshop. Then the javascript should return a value like "workshop finished", "workshop in progress", "workshop to come" (depending on wheiter todays date is before, during, or after that specific date range). I'll call the function 4 different times - each with a different range of dates.
So for example, If the first set of dates are: 6th February till 13th March 2014, then how would I call the javascript function? This is what I have so far:
In the html - at the point where I want the status to be displayed, I tried this:
<script language="JavaScript" type="text/javascript">
<!--//
document.write(displayStatus(02062014, 03132014));
//-->
</script>
<noscript></noscript>
I know that the above date formating is probably wrong that I am trying to send to the function, but I am not sure what format is needed to do a date compare. (Note: the empty noscript tags are because if scripting is turned off, I don't want anything displayed.)
I've started the function like this (found inside status-date.js file):
function displayStatus(fromDate,toDate) {
todayDate = new Date();
// this is a comment for code that needs to be written:
//
// magic happens here that compares today's date to the fromDate and toDate
// and returns th appropriate status line
//
// the rest below is how I think the status is returned to the html
// (I'm using 'in progress' as a test example)
var dateStatus = "in progress"
return dateStatus;
}
Note: the function is loaded in from the head section as follows:
<script src="assets/js/status-date.js" language="javascript" type="text/javascript"></script>
Even with this simple function.. that basically gives me the status without any calculations, just so I can test the comunication between HTML and function.. it doesn't display anything. So I can't really move forward until I figure out this basic step first.
So, could some kind sole help me figure this out.
How to properly send formated date parameters to the javascript function.
How to display the status results that need to be returned to the html
How do you (inside the function) check if todays date falls within a range of provided dates.
Thanks for any help provided.
SunnyOz
I believe that you are looking for something like this...
function displayStatus(fromDate,toDate) {
var status;
var today = new Date();
today = Date.parse(today);
if(today >= fromDate && today <= toDate) {
status = 'In Progress';
} else if(today > toDate) {
status = 'Workshop Finished';
} else {
status = 'Workshop To Come';
}
return status;
}
<script>
window.onload = function(){
var startDate = new Date(2014,1,6); //6th February
var endDate = new Date(2014,2,13); //13th March 2014
document.write(displayStatus(Date.parse(startDate), Date.parse(endDate)));
};
</script>
Here are some other helpful resources:
Compare two dates with JavaScript
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

Function with If/Else Statement - Comparing Dates

I am working with a function and I am trying to write an if-else statment that compares a textfield aganist some dates.
This is what my function looks like right now:
function updateSwitch(){
if (effDate.getValue() > effDate.getValue(new Date())){
submitButton.disable();
}
else{
submitButton.enable();
}
}
I am trying to compare the dates among the same textfield. I am trying to say that if the date enetered in the textfield is in the future (any day after tomorrow), then disable the submitButton. I know that
the function works if I compare the textfield aganist a different textfield, but I cannot get it to work within the same textfield.
I'm not sure how you have your dates constructed. Is effdate been constructed with the Date object? If so, may I suggest using valueOf(). It'll return the primitive value - or the date in milliseconds. This should allow for a more consistent comparison.
function updateSwitch(date){
var effDate = Date.parse(date);
var curDate = new Date();
if (effDate.valueOf() > curDate){
submitButton.disable();
}
else{
submitButton.enable();
}
}

Categories

Resources