comparing dates using script in forms - javascript

I am trying to validate date based on date entered in first textbox. If second textbox exceeds one year from the date entered in first textbox, then it should display an alert and blank the second date field textbox. Both the textboxes are readonly and gets the values from calender. I tried the below code but the alert is popping up even if the year is not more than a year. Also ,is it possible to pass 'name3' and 'name4' IDs as parameters. I need to apply this code to 10 rows.
<script>
function fixup()
{
var parts = document.getElementById('name3').value.split("-");
parts[2] = Number(parts[2]) + 1;
var pj = parts.join("-");
var x=document.getElementById('name4').value;
if(x>pj)
{
alert("Expiration date should not be greater than one year from start date");
document.getElementById('name4').value = "";
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return fixup()">
<table>
<tr>
<td><input type="text" name="soname3" id="name3" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name3','MMddyyyy','dropdown',false,'12')" /></td>
<td><input type="text" name="soname4" id="name4" size="15" readonly="readonly">
<img src="../Image/cal.gif" id="" style="cursor: pointer;" onclick="javascript:NewCssCal('name4','MMddyyyy','dropdown',false,'12'); " /> </td>
</tr>
</table>
<input type="submit" value="Submit">
</form>
I did Below code after suggestions by dm03514. but validation is not working..
function test()
{
start = document.getElementById('name3').value;
end = document.getElementById('name4').value;
compare(start, end);
}
function compare(sDate, eDate)
{
function parseDate(input) {
var parts = input.match(/(\d+)/g);
return new Date(parts[2], parts[0]-1, parts[1]); //parts[2] is year, parts[0] is month and parts[1] is date.
}
var parse_sDate = parseDate(sDate);
var parse_eDate = parseDate(eDate);
parse_sDate.setDate(parse_sDate.setFullYear(parse_sDate.getMonth() + 12));
if(parse_sDate>parse_eDate)
{
alert("End date should not be greater than one year from start date");
}
}

I would strongly recommend using a library like moment.js for handling dates. It has extensive date formatting and parsing features as well as comparison helpers:
var d1 = moment(document.getElementById('name3').value, 'YYYY-MM-DD');
var d2 = moment(document.getElementById('name4').value, 'YYYY-MM-DD');
var diff = d2.diff(d1, 'years');
if (diff > 0) {
alert("Expiration date should not be greater than one year from start date");
}
See also:Compare two dates in JS

Related

Select a date 7 days after current date in javascript

I have input in html like this:
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
I would like to select a date that is more than 7 days from the current date, if I select a date before 7 days from current, it should prompt saying "Wrong date selected"
How do I do that in javascript?
I tried the following:
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
It gives the date correctly. How do I use this to compare if date is 7 after or not and prompt accordingly?
Thanks!
UPDATE:
<html>
<body>
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
</body>
</html>
<script>
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e)
{
var selectDate = e.target.value
var startDate = new Date(Date.parse(selectDate));
console.log(startDate);
var dateAfter7Days = new Date(new Date().getTime()+(7*24*60*60*1000))
console.log("7 days " + dateAfter7Days);
if (startDate => dateAfter7Days )
{
console.log("Allow");
}
else
{
console.log("Don't allow");
}
}
</script>
I am getting "Allow" for any date I select.
The point is comparing two date values. If current date - selected date > 7 then it should print prompt. The problem is how to get selected date.
You can get the selected date from the input tag by event value. On changed date, the value get logged.
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e) {
console.log(e.target.value);
}
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
var date = new Date();
var next_seven_date = d.getDate()+7;
var current_month = d.getMonth();
current_month++; // month start from 0 then we need to +1
var current_year = d.getFullYear();
var weekDate =(next_seven_date + "/" + current_month + "/" + current_year);
date.setDate(weekDate);
Since your problem is to compare dates not creating them I have updated my answer which might hlp you
var currentDate= new Date();
currentDate= new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate(),0,0,0)
var idealDifference= (7*24*60*60*1000);
//In your case this date might comes from some date selection user control. Be aware to make the time part of each date to same
var userSelectedDate = new Date(2021, 04, 04,currentDate.getHours(),0,0,0)
if((userSelectedDate.getTime()-currentDate.getTime())>=idealDifference)
{
console.log(userSelectedDate, ' is after 7 days from ',currentDate)
}
else
{
console.log(userSelectedDate, ' is before 7 days from ',currentDate)
}
Note: It is important to unset the time part of both the dates before comparing for this logic to work

Date comparison on input, client side MVC

I have a function that compares 2 dates, Start_Date and End_Date. If the start date is greater then the end date, alert a message saying "The start date exceeds End Date. Please check the date and re-enter it." Also, this should be compared right after a click away from the text box.
The below code doesn't seem to be doing justice. Any suggestions?
JS Code:
$("td[start] > input").on("change", function () {
alert("here first");
var cur_td = $(this).closest("tr");
var startdate = $(this).val();
var enddate = cur_td.find("td[end]").text();
var d1 = Date.parse(startdate);
var d2 = Date.parse(enddate);
checkdates(d1, d2);
});
function checkdates(s_date, e_date) {
if (s_date > e_date) {
alert("The date " + s_date + " exceeds End Date. Please check the date and re-enter it.");
}
}
Razor View:
<td start><input class="start" id=#item.ID type="text" actual="1" value='#(item.Start_Date == null ? "" : Convert.ToDateTime(item.Start_Date).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
<td end><input class="end" id=#item.ID type="text" actual="1" value='#(item.End_Date == null ? "" : Convert.ToDateTime(item.End_Date).ToString("MM-dd-yyyy"))' readonly="readonly" /></td>
You try 'keyup' instead of 'change.
$("td[start] > input").on("keyup", function () { })
or
if you want to use on('change'), then you must use input type date or any date-picker.like
<input class="start" id=#item.ID type="date" actual="1" value='#(item.Start_Date == null ? "" : Convert.ToDateTime(item.Start_Date).ToString("MM-dd-yyyy"))' readonly="readonly" />

Subtract date, month and years dynamically and put data as days using Jquery

I want to subtract a user input years from another input years, but so far I had no luck.
I'll create a snippet where you can play.
What I'm trying to do is to make an input field (A) to enter years only. Then after that select any date and subtract it from the input year (A) (date and month are fixed like 31.03.input_year)...
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = year_enter+'-03-31';
var new_date = $('#new_date').val();
if(year_enter != '') {
//alert(current_year);
}
if(new_date != '') {
//alert(new_date);
var total = new_date - current_year;
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
I always get NaN value, my subtract method is incorrect I guess. I tried using setDate(), getDate() etc, but I don't understand the logic.
Thanks in advance...
You can use new Date() to type cast them into date in order to do arithmetic
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = new Date(year_enter + '-03-31');
var new_date = new Date($('#new_date').val());
if (year_enter != '') {
}
if (new_date != '' && year_enter != '') {
if (current_year < new_date) {
$('#answer').val('A must be greater than B');
return;
}
var total = Math.round(Math.abs((current_year.getTime() - new_date.getTime()) / (24*60*60*1000)));
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001"><span style="opacity: 0.5;"> this currently has fixed -month-day(-03-31) </span>
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
Dates can be tricky to handle, but the moment library makes it a lot easier. In my example I take the input of the two fields, parse them into a moment object and calculate their difference in a duration. You can read more on duration in the Moment.js docs.
The code snippet difference is expressed in days. In case you want to change it to months, or years, update the below line.
log(Math.round(duration.as('days')) + 'days');
You can also include several if statements, to check if the difference is a year, display the result in years. If not, and there's a full month, express the result in months and so on.
Here's a working example in days.
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
NOTE: There are a few discussions out there on how to format a date/duration, e.g. 1 year, 2 months, 5 days. Have a look at a possible solution at these discussions if you want something like this.
How can I format time durations exactly using Moment.js?
How do I use format() on a moment.js duration?

Text box entered date should be in dd/MM/yyyy while creating date object using Jscript

enter code hereSuggest me on this..
While creating Date ref(java script), text box value should be treated as dd/MM/yyyy format..
function myFunction1(a)
{
//Here the input format should be dd/MM/yyyy...
//But Date ref taking it as MM/dd/yyyy
var x=new Date(a);
alert(x);
if(x>new Date())
{
alert("Wrong date");
}
else
{
alert("Success");
}
}
----
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onClick="myFunction1(document.getElementById('textbox1').value)" type="button" value="Execute" />
Try this:
var dateString = document.getElementById('<textboxid>').value;
var day = parseInt(dateString.substring(0,2));
var month = parseInt(dateString.substring(3,5));
var year = parseInt(dateString.substring(6,10));
alert(new Date(year, month - 1, day));
To Validate Date, Use this code:
alert(/^(0[1-9]|[12][0-9]|3[01]|[1-9])[- /.](0[1-9]|1[012]|[1-9])[- /.](\d{4})$/.test(dateString));
It will return true if the date is valid else return false.

javascript add number of input fields equal to the number of months

I have two input fields with date1 and date2.Below this two fields i need a button that when i press it, will create a number of input fields equal to the number of months between the 2 date fields.
For example i have date1=2012-03-21 and dat2=2012-06-21. It should generate 3 input fields
Can you help me with this one?
Let's assume the HTML looks something like this:
<div id="dateRange">
<input type="text" id="startDate">
<input type="text" id="endDate">
</div>
<div id="monthlyEntries"/>
Now, a month is not a uniform number of days ("30 days has September, April, June,and November..."), so I'm guessing the day portion of the dates don't matter.
Then, the javascript to call on change (or clicking a button, or whatever), would look something like this:
function buildMonthlyEntries() {
var startDate = new Date(document.getElementById('startDate').value);
var endDate = new Date(document.getElementById('endDate').value);
if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
var entryCount = (endDate.getMonth() + endDate.getFullYear()*12) - (startDate.getMonth() + startDate.getFullYear()*12);
var monthlyEntries = document.getElementById('monthlyEntries');
monthlyEntries.innerHTML = "";
for(var i = 0; i < entryCount; i++) {
var textElement = document.createElement('input');
textElement.setAttribute('type', 'text');
textElement.setAttribute('id', 'entry' + i);
monthlyEntries.appendChild(textElement);
}
return null;
}
You can run a loop based upon the difference in the dates. In pseudo code it would be something like
var difference = month2 - month1;
for(x=0;x<difference,x++){
add inputfield;
}

Categories