Select a date 7 days after current date in javascript - 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

Related

Trying to only allow date picking to be between 45-90 days from today's date

This is the code I have so far but I am not sure how to alter this function to also check if the selection was made after 90 days. What I have so far is when you click the date picker, it will jump to 45 days from today and not allow user to choose anything from prior, but the problem is that it will allow past 90 days which is what i dont want.
https://jsfiddle.net/dwyvtajg/
<label id="asterisk">*</label> <label class="description" for="element_2">Event Date:</label><br /><label>Reservations must be made between <b>45-90 days in advance</b> of the event date</label> <br /><input onclick="one()" required="" type="date" oninput="this.className = ''" name="Event-Date" id="datepicker1" min="2019-10-02" />
<script>if ( $('#datepicker1')[0].type != 'date' ) $('#datepicker1').datepicker();</script>
<script>
function formatISOLocal(d) {
let z = n => ('0' + n).slice(-2);
return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}
function one() {
let inp = document.querySelector('#datepicker1');
let d = new Date(new Date().getTime()+(45*24*60*60*1000));
inp.min = formatISOLocal(d);
inp.defaultValue = inp.min;
d.setFullYear(d.getFullYear() , d.getMonth() + 6);
inp.max = formatISOLocal(d);
// Debug
console.log(inp.outerHTML);
}
</script>
thanks for the help everyone.... editing this line fixed it!!!
d.setFullYear(d.getFullYear() , d.getMonth() , d.getDate() +45);
Definitely take like an hour to review the docs. You're making things so much harder on yourself otherwise.
For instance, setting a min and max date - voila:
$(function() {
$( "#datepicker1" ).datepicker({
maxDate:'+90d',
minDate: '+45d',
onSelect: function(date) {}
});
});

Add one hour to string on client side

I have two timepicker in my view
#Html.Kendo().TimePickerFor(m=>m.AttendeeStartTime).Format("HH:mm")
#Html.Kendo().TimePickerFor(m=>m.AttendeeEndTime).Format("HH:mm")
This is how it looks
and here is rendered HTML for From Timepicker,
<input data-val="true" data-val-required="The AttendeeStartTime field is required."
id="AttendeeStartTime" name="AttendeeStartTime" type="text" value="09:00" data-role="timepicker"
class="k-input valid" role="textbox" aria-haspopup="true" aria-expanded="false" aria-
owns="AttendeeStartTime_timeview" aria-disabled="false" aria-readonly="false" style="width: 100%;">
Whenever there is change in From timepicker, how can I add one hour to its value and set to to To timepicker?
This is what I have done,
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//var date = new Date();
endTime.value($(this).val());
alert(endTime.value());
This only sets the To value to the same as From when there is change, but I want to add an hour or some timespan to it.
How should i do that?
Use this:
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//try getting the date from the date picker
var date = $("##Html.IdFor(m=>m.AttendeeStartTime)").data("kendoTimePicker").value();
if (date) {
//convert the string to a date
date = new Date(date); //you can probably skip this step since the Kendo DatePicker returns a Date object
//increase the "hours"
date.setHours(date.getHours() + 1);
//set it back in the "to" date picker
$("##Html.IdFor(m=>m.AttendeeEndTime)").data("kendoTimePicker").value(date);
//alert(endTime.value());
}
}
You can write a custom function like this,
function addMinutes(time, minsToAdd) {
function z(n){ return (n<10? '0':'') + n;};
var bits = time.split(':');
var mins = bits[0]*60 + +bits[1] + +minsToAdd;
return z(mins%(24*60)/60 | 0) + ':' + z(mins%60);
}
addMinutes('05:40', '20'); // '06:00'
addMinutes('23:50', 20);
Your scenario should be,
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//var date = new Date();
endTime.value($(this).val());
addMinutes($(this).val(), '60');
alert(endTime.value());

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.

comparing dates using script in forms

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

Validation with KendoUI datetime

Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.

Categories