How to pass date id from one jsp to another jsp page - javascript

I am calculating the price of a ticket with discount on weekdays and weekends based on the time duration.So, i gave inputs of duration and date using datepicker plugin which is in Above Page. For this i am getting proper result.But i have to create two different jsp pages(date.jsp and cal.jsp).
In 1st jsp page(date.jsp) i am selecting date using datepicker. And in 2nd jsp page(cal.jsp)
I have written a method ->[caluculate(#dateid,#duratiionid)] to calulate the price by taking inputs as time duration.
Here My Question is how shall i pass [#dateid] from 1st jsp page(date.jsp) to 2nd jsp page(cal.jsp)
so that i can pass both the id's in this method->[caluculate(#dateid,#duratiionid)].
<div id="container">
<div id="form">
<form id="book_court">
<div class="fieldset">
<fieldset>
<legend class="visuallyhidden">Booking Details</legend>
<h2>Booking Details</h2>
<p>
<label for="date">Date<br/><span id="dateNote">Firefox does not have a HTML5 datepicker yet.</span></label>
<input type="date" name="date" id="date" min="today" required />
</p>
<p>
<label for="tickets_duration"> Hours</label>
<input type="number" min="1" name="tickets_duration" id="tickets_duration" required />
</p>
<p>
<label>Total Price</label>
<span id="total_price">(enter data first)</span>
</p>
<div id="submit_wrapper">
<input type="submit" id="submit" value="Book Court" />
</div>
</fieldset>
</div>
</form>
</div>
</div>
<script id="worker" type="javascript/worker">
self.onmessage = function msgWorkerHandler(event){
var jsonString = event.data;
var day = jsonString.day;
var tickets_duration = jsonString.tickets_duration;
// set price of each hours as Rs. 200 and 300
var totalPriceOnWeekday = tickets_duration * 200;
var totalPriceOnWeekends=tickets_duration * 300;
// 10% discount if on weekday and 15% on weekends
if(day > 0 && day < 6){
totalPriceOnWeekday = totalPriceOnWeekday - 0.10 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekday);
}else if(day == 0 || day == 7){
totalPriceOnWeekends = totalPriceOnWeekends - 0.15 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekends);
}
}
</script>
<script>
$(document).ready(function(){
// first check the movies already book
// apply jQuery UI Redmond theme to 'Book Tickets' button
$("#submit").button();
// calculateTotalPrice on keyup or on change of movie/date/tickets
$("#date, #tickets_duration").change(calculateTotalPrice);
// on form submit
$("#book_court").submit(function(event){
// prevent on submit page refresh
event.preventDefault();
// check locally stored data
// clear the form
$( '#book_court' ).each(function(){
this.reset();
});
// reset (enter data first) message
$("#total_price").html("(enter data first)");
// update movies booked list
});
// set minimum date in datepicker as today
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("date")[0].setAttribute('min', today);
});
function calculateTotalPrice(){
if($("#tickets_duration").val() != "" && $("#date").val() != ""){
if(window.Worker){
// create web worker
var blob = new Blob(
[document.querySelector("#worker").textContent],
{type: 'text/javascript'});
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(event){
$("#total_price").html(event.data);
}
worker.onerror = function(errorObject){
$("#total_price").html("Error: " + errorObject.message);
}
var date = new Date($('#date').val());
// get day
var day = date.getDay();
// get number of booked shows
// send JSON data to worker
var jsonData = {'day': day, 'tickets_duration': Number($("#tickets_duration").val())};
worker.postMessage(jsonData);
}
}
}
</script>

If you want to share a value cross-pages, you can use cookie to store the value. Another option is localStorage/sessionStorage if you are using HTML5.
So, in the first page (date.jsp), when user select a date, you can store that selection to cookie, in the second page (cal.jsp) you can read that value from cookie and then do your calculation.
I suppose that you are able to post the date string back to servlet. In the servlet, you are using that date string to check for ticket validity. You just don't know how to check if the date is weekday or weekends. If so you can you the java.util.Calendar for that purpose.
EDITED
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date yourDate = formatter.parse(dateInString);
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

Related

Limit the date to today and block the previous dates

I am beginner in JavaScript, I know the subject exists on StackOverFlow as here below but I don't understand.
Compare two dates with JavaScript
I would like to handle the previous dates for example: We are on 28-05-2020, if the user enters on 27-05-2020 an error message should appear.
For information, I am obliged to use JavaScript to handle the dates.
function validation()
{
const date_start = document.getElementById('date_start').value;
const inputDate = new Date(date_start);
const dayFromImputDate = inputDate.getFullYear(); // previous day
const now = new Date();
const dateNow = now.getFullYear();
if(dayFromImputDatee < dateNow) {
document.getElementById('date_startError').innerHTML = " ** Error date ! ";
return false;
}
if(date_start == ""){
document.getElementById('date_startError').innerHTML = " ** date empty ! ";
return false;
}
console.log("Date is valid");
return true;
}
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8">
<title>Titre de la page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="#" onsubmit="return validation()" >
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
</body>
</html>
Thank you very much for your help and your time.
You can check if input date is less than today's date using < operator
const form = document.querySelector('form');
const error = document.getElementById('date_startError');
function validation(event) {
event.preventDefault();
const startDate = form.elements['date_start'].value;
if (!startDate) {
error.innerHTML = " ** date empty ! ";
return;
}
const inputDate = new Date(startDate).getDate();
const today = new Date().getDate();
if (inputDate < today || !inputDate.valueOf()) {
error.innerHTML = " ** Error date ! ";
return;
}
error.innerHTML = "date is valid";
}
<form action="#" onsubmit="validation(event)">
<br>
<label>Date start : </label>
<br>
<input type="date" name="date_start" id="date_start" placeholder="2020-05-28">
<br>
<span id="date_startError"></span>
<br>
<input type="submit" value="ok">
</form>
Because HTML5 already has min and max attributes for the date input type, you don't need to implement a separate validation function to accomplish this. Here is a simpler way:
var date = new Date();
var iso_date = date.toISOString().substring(0, 10);
document.getElementById("date_start").setAttribute('min', iso_date);
Basically, you just get a new Date() object, extract and format it into an ISO 8601 date format, and set it into the min attribute. This also limits the browser selection calendar to future dates only.
If I understand the problem correctly you are trying to restrict a date form input to the current day or some future date.
To check whether a date is valid you could do this:
let earliestPossibleDate = new Date(
now.getFullYear(), now.getMonth(), now.getDate()
);
let isValidDate = date_start >= earliestPossibleDate
Three things:
You need to get your Current Date and set time to start of day.
You need to get your Selected Date and set time to start of day
Compare whether Selected Date is Greater or Equal to the Current Date.
Note that when you compare dates, you need to also consider the time.
Most calendar tools, include the time as a response to the selected date. You need to be aware of that.
This doesn't include other date validations. This will only solve the current problem at hand. Hope this helps! =)
const isValidDate = (selectedDate) => {
const currentDate = new Date();
// reset to start of day
currentDate.setHours(0);
currentDate.setMinutes(0);
currentDate.setSeconds(0);
currentDate.setMilliseconds(0);
const newDate = new Date(selectedDate);
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
return newDate.getTime() >= currentDate.getTime();
}
To use, simply throw the selected date in the function. Should return true if the date is greater or equal to the date today.
isValidDate(selectedDateFromDatePicker);

Age validation using dd/mm/yyyy

I am trying to validate a form I have for age validating using javascript but it doesn't seem to be working.. not sure why.
Basically the date of birth is entered : dd/mm/yyyy and I need to make sure that in order to submit the form the age of the person is between 15 - 80.. I have tried validating this way but doesn't seem to work.
Html
<label>
Date of birth:
<input type="text" name="birth date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
Javascript
var birthDate = document.getElementById("DOB").value;
if (2019 - birthDate < 15 || 2019 - birthDate > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
return result;
So, based on your comment, you have a text box as such:
<form>
<input type="text" name="birth date" id="DOB" placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}" required="required"/></label>
</form>
Therefore, document.getElementById("DOB").value; will be of the format dd/mm/yyyy.
So, if you are just checking the year, this should do the trick:
onload = function() {
var form = document.getElementById("form"); //assuming this is your form's ID
form.onsubmit = validate;
}
function checkAge() {
var currentYear = new Date().getFullYear();
var birthDate = document.getElementById("DOB").value;
var errMsg = ""; //this line was missing from my code, and preventing it from working.
//turning "dd/mm/yyyy" into an array of the form { "dd", "mm", "yyyy" }, and taking the "yyyy" part
var birthYear = birthDate.split("/")[2];
var age = currentYear - birthYear;
if (age < 15 || age > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
return false; //form won't submit
}
return true; //form will submit
}
As you can see, I also used getFullYear() so that we don't hard code a fixed current year.
But it would probably be cleaner if you use an <input type="date"> element rather than a text box.
document.getElementById("DOB").value is a string, not a date, so you need to convert it. For that there are different methods; one is to convert the string to YYYY-MM-DD format and pass that to the Date constructor.
Moreover, someone's age changes on their birthday, not at the change of a calendar year, so you need a different logic to get their age. One way is to precalculate the date of 15 years ago and of 81 years ago, and test that the entered birthdate lies between these two extremes.
var DOB = document.getElementById("DOB");
var output = document.getElementById("output");
var go = document.getElementById("go");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Function returns true when age is OK, false otherwise
function check() {
var birthDate = new Date(DOB.value.replace(/(..)\/(..)\/(....)/, "$3-$2-$1"));
return birthDate <= fifteenYearsAgo && birthDate > eightyOneYearsAgo;
}
go.addEventListener("click", function() {
if (check()) {
output.textContent = "Your age is OK";
} else {
output.textContent = "Your age must be between 15 and 80";
}
});
Birthdate: <input id="DOB"><button id="go">Go</button>
<div id="output"></div>
HTML5
If you are certain about your clients having HTML5 support, then use type="date" for your input element, and dynamically set the min and max attributes of a date typed input element and rely on form validation. If the form gets into the submit handler, you can be sure the validations passed:
var DOB = document.getElementById("DOB");
var form = document.querySelector("form");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setHours(0, 0, 0, 0);
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setHours(0, 0, 0, 0);
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Border case: in leap years next condition could be false
if ((new Date()).getDate() === eightyOneYearsAgo.getDate()) {
eightyOneYearsAgo.setDate(eightyOneYearsAgo.getDate()+1);
}
DOB.setAttribute("min", eightyOneYearsAgo.toLocaleString("se").slice(0,10));
DOB.setAttribute("max", fifteenYearsAgo.toLocaleString("se").slice(0,10));
form.addEventListener("submit", function(e) {
alert("Your age is OK");
e.preventDefault();
return false;
});
function validationMessage() {
DOB.setCustomValidity("");
const msg = DOB.checkValidity() ? ""
: DOB.validity.valueMissing ? "This field is required"
: DOB.validity.rangeOverflow ? "You must be at least 15"
: DOB.validity.rangeUnderflow ? "You must be at most 80"
: "Enter a valid date"
DOB.setCustomValidity(msg);
}
DOB.addEventListener("input", validationMessage);
validationMessage();
<form>
<label>
Date of birth:
<input type="date" name="birth date" id="DOB" required="required"/>
</label>
<button id="go">Go</button>
</form>
document.getElementById("DOB").value; will give you something like 10/10/2000 and performing arithmetic operations on this string will result in NaN. That must be causing an issue.
Validating date is a more complex than you imagine. There are a lot of things that you need to consider. Use libraries like moment to help you in validating dates.
Edit: Use moment's Difference method to calculate the age.
You can use built in min and max props for input. Try something like this.
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="15" max="80" required>
<button onclick="myFunction()">OK</button>
<p>If the age is less than 15 or greater than 80, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
Theoretically this should work.
Since you are using pattern and required I assume that you want the error message (if the age is out of range) to be shown to the user in the same way as if the entered date is in the wrong format or is missing. That can be achieved with setCustomValidity.
If you add an event listener of the input event on the DOB-element, you can run a function that checks if the entered age is in rage. It will set the custom error message if the age is out of range, or if the entered date is invalid. Otherwise it let the browser handle the error (if it is missing or of wrong pattern).
function validateDOB(event) {
const minAge = 15, maxAge = 80;
// No custom error message. The broswer will complain if the input isn't in the
// correct form, or if the value is missing since the element has "pattern" and
// and "required".
this.setCustomValidity('');
// Check if there are any other errors
if ( !this.validity.valid ) return;
// Check format of input, and split it into parts
const dobArrayText = this.value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
// dobArrayText is null if not in correct format. Let the broswer handle the error.
if (!dobArrayText) return;
// Decode dobArrayText to numeric values that can be used by the Date constructor.
const dob = {
year : +dobArrayText[3],
month : (+dobArrayText[2]) - 1, // month is zero based in date object.
day : +dobArrayText[1]
}
const dobDate = new Date( dob.year, dob.month, dob.day );
// Check validity of date. The date object will accept 2000-99-99 as input and
// adjust the date to 2008-07-08. To prevent that, and make sure the entered
// dobDate is a valid date, I check if the entered date is the same as the parsed date.
if (
!dobDate
|| dob.year !== dobDate.getFullYear()
|| dob.month !== dobDate.getMonth()
|| dob.day != dobDate.getDate()
) {
this.setCustomValidity('Invalid date');
return;
}
// Calc minAgeDate and maxAgeDate
const minAgeDate = new Date(dob.year + minAge, dob.month, dob.day);
const maxAgeDate = new Date(dob.year + maxAge, dob.month, dob.day);
// Get todays date and set Hours, Minutes, Seconds and Milliseconds to 0.
const todayTimestamp = new Date().setHours(0,0,0,0);
// Check validity and set a custom error message if needed.
if ( todayTimestamp < minAgeDate ) {
this.setCustomValidity(`Sorry, you must be older than ${minAge} years old`);
}
else if ( todayTimestamp >= maxAgeDate ) {
this.setCustomValidity(`Sorry, you must be younger than ${maxAge} years old`);
}
}
function formInit() {
document.getElementById('DOB').addEventListener("input", validateDOB);
}
window.addEventListener('DOMContentLoaded', formInit);
<form id="myForm">
<label>
Date of birth:
<input type="text" name="birth_date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
<button type="submit">Submit</button>
</form>

How to show different time period on Sunday - Jquery datetimepicker

I would like to set a specific time period only on Sunday. So every other day the 'allowTimes' is from 18:00 to 22:30 but on sunday its 12:30 till 20:30. I am searching solution from last two days but haven't found it.
HTML
<div class="form-group">
<input type="text" id="date" name="txtDate" class="form-control" placeholder="Date">
</div>
<div class="form-group">
<input type="text" id="time" name="txtTime" class="form-control" placeholder="Time">
</div>
JQUERY
//Time Picker
$('#time').datetimepicker({
datepicker:false,
format:'H:i',
step:15,
allowTimes:['18:00','18:15','18:30','18:45','19:00','19:15','19:30','19:45','20:00','20:15','20:30','20:45','21:00','21:15', '21:30', '21:45', '22:00', '22:15','22:30']
});
// Date Picker
$('#date').datetimepicker({
timepicker:false,
format:'d/m/Y',
});
Your question is trickier than it seems because jQuery DateTimePicker in an instance and the fact that once initialized, you can't change the options.
But there always is a walk-around!
The trick here is to "destroy" the instance on the time input when the day number changes (0 for sunday to 6 for saturday) and reinitialise it with the right schedule. Now if the selected time does not exist in the new schedule, force the user to re-select the time.
Looks simple? See the code:
console.clear();
var schedule_week = ['18:00','18:15','18:30','18:45',
'19:00','19:15','19:30','19:45',
'20:00','20:15','20:30','20:45',
'21:00','21:15','21:30','21:45',
'22:00','22:15','22:30'];
var schedule_sunday = ['12:30','12:45',
'13:00','13:15','13:30','13:45',
'14:00','14:15','14:30','14:45',
'15:00','15:15','15:30','15:45',
'16:00','16:15','16:30','16:45',
'17:00','17:15','17:30','17:45',
'18:00','18:15','18:30','18:45',
'19:00','19:15','19:30','19:45',
'20:00','20:15','20:30'
];
var prev_dayNum;
var schedule_used = schedule_week; // Use the week schedule by default.
// Function to initialise the time picker input.
function initTime(){
$('#time').datetimepicker({
datepicker:false,
format:'H:i',
step:15,
allowTimes: schedule_used
});
}
// On load time initialisation.
initTime();
// Initialise the date input.
$('#date').datetimepicker({
timepicker:false,
format:'d/m/Y',
// On change callback
onChangeDateTime:function(dp,$input){
var dateVal = $input.val();
var timeVal = $('#time').val();
//console.log(dateVal +" - "+ (timeVal||"No Time"));
// Because of the d/m/Y format, have to process the date a bit to get the day number.
val = dateVal.split("/");
var dayNum = new Date(val[2]+"/"+val[1]+"/"+val[0]).getDay();
//console.log("dayNum: "+dayNum);
// if dayNum is zero (sunday), use sunday schedule... Else use the week schedule.
schedule_used = (dayNum == 0) ? schedule_sunday : schedule_week;
// If the dayNum changed.
if( prev_dayNum != dayNum ){
console.log("Changed day!");
// Re-initialise datetimepicker
$('#time').datetimepicker("destroy");
initTime();
// If the actual time value is not in schedule.
if($.inArray(timeVal,schedule_used) == -1){
console.log("Wrong time!");
// Clear the time value.
$('#time').val("");
// Focus the time input so it's obvious the user has to re-select a time.
$('#time').focus();
}
}
// Keep this dayNum in memory for the next time.
prev_dayNum = dayNum;
}
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.js"></script>
<div class="form-group">
<input type="text" id="date" name="txtDate" class="form-control" placeholder="Date">
</div>
<div class="form-group">
<input type="text" id="time" name="txtTime" class="form-control" placeholder="Time">
</div>
Now as you can see, the time schedule is different for sundays than the other days. And it "forces" the user to enter/re-enter a time only when what's entered does not fit the schedule.
I left the console logs uncommented in CodePen.

Firefox date format

I have created a webpage which calculates the weeks and days between two dates.
In chrome this page works and gives me the output of 4 weeks and two days for the dates 01/01/2016 and 01/31/2016 but firefox gives me the output of 130 weeks and two days.
How would I got about changing this to get the output of chrome.
Many thanks
<html>
<head>
<title>Time Between Dates Calculator</title>
<script src="dateCalc.js"></script>
</head>
<body>
<h1>Calculate the Amount of Time Between Dates:</h1>
<form>
Enter Date 1 (mm/dd/yyyy): <input type="date" id="date1" name="date1" required> <br />
Enter Date 2 (mm/dd/yyyy): <input type="date" id="date2" name="date2" required> <br />
<input type="submit" onclick="datecalc()" Value="Get Weeks and days">
</form>
</body>
</html>
***********************************************************************
function datecalc()
{
firstDate = document.getElementById("date1").value;
secondDate = document.getElementById("date2").value;
/*window.alert(firstDate);
window.alert(secondDate);*/
firstDateMs = new Date(firstDate).getTime();
secondDateMs = new Date(secondDate).getTime();
msPerDay = 24 * 60 * 60 * 1000;
msLeft = (secondDateMs - firstDateMs);
daysLeft = Math.round(msLeft/msPerDay);
weeksLeft = Math.round(daysLeft/7);
total = (daysLeft-(weeksLeft*7))
window.alert("The difference between these days is: " + weeksLeft + " weeks and " + total + " days.");
}
one solution is to use .split("/") on your input strings, then use the
new Date(year, month, day); constructor.
Also January is 0 and December is 11 in Javascript date
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date
this will remove any ambiguity from possible string interpretation of the date.
firstDate = document.getElementById("date1").value;
secondDate = document.getElementById("date2").value;
/*window.alert(firstDate);
window.alert(secondDate);*/
firstDate.split("/");
secondDate.split("/");
firstDateMs = new Date(parseInt(firstDate[2]), parseInt(firstDate[0]) - 1, parseInt(firstDate[1])).getTime();
secondDateMs = new Date(parseInt(secondDate[2]), parseInt(secondDate[0]) - 1, parseInt(secondDate[1])).getTime();
The submit listener should be on the form, not the submit button, since the form can be submitted without clicking the button. Also, the date strings should be manually parsed to dates and since they depend on user input, the values validated. It can also make life easier if a reference to the form is passed by the handler so controls are accessed by name rather than getElementById.
Input type date is not well supported and creates more issues than it solves for now, so better to use type text (or use your own date picker). The following uses input type text and manually parses and validates the string in m/d/y format.
For a real form, it would be better to validate each date separately and put an error message for the one(s) that are invalid, also to echo the parsed date to the screen so the user can see that the code is using the date as they expect (e.g. 1/2/2016 comes out as 2 January not 1 February).
Some code…
function datecalc(form) {
var d1 = parseMDY(form.date1.value);
var d2 = parseMDY(form.date2.value);
var msDay = 8.64e7;
var msWeek = msDay * 7;
var result;
// Deal with in valid input
if (isNaN(+d1) || isNaN(+d2)) {
result = 'Invalid date';
} else {
// Get weeks and days
var diff = d2 - d1;
result = (diff/msWeek | 0) + ' weeks ' +
Math.round((diff % msWeek)/msDay | 0) + ' days';
}
// Should return an array of say [weeks, days] and leave formatting
// to some other function.
form.result.value = result;
}
function parseMDY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[0], b[1]);
return d && d.getMonth() == b[0]? d : new Date(NaN);
}
<form onsubmit="datecalc(this); return false;">
Enter Date 1 (mm/dd/yyyy): <input type="text" name="date1" value="3/1/2016"><br>
Enter Date 2 (mm/dd/yyyy): <input type="text" name="date2" value="3/23/2016"><br>
<input type="reset"> <input type="submit" Value="Get Weeks and days"><br>
<input type="text" name="result" readonly>
</form>
I guess you're rounding the days to remove daylight saving errors, be careful with that. An alternative is to get the difference in days from the date values and not create date objects at all. That removes any issues with DST (but validating the dates takes about 3 lines more code).

PHP: Date range selection automatically

I have 3 input fields all together.
Contract period: 1 years(for example)
start date : 30 - 1- 2012 (for example)
end date : ????
(Can we get the end date automatically according to the contract period mentioned, which mean if the date after 1 year is 30-1-2013 can we get it automatically in the third field after mentioning the first and second field).
Possible, using onSelect option of jQuery datepicker.
1) get the value of contract year and parse it as integer.
var addYears = parseInt($('#contract').val(), 10);
2) Split the selected date in startDate, as below
var t = date.split('/');
3) Now add the years and parse it as Date object.
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
Finally,
HTML:
In years only:
<input id="contract" type="text" />
<input id="start" type="text" />
<input id="end" type="text" />
JS:
$('#end').datepicker();
$('#start').datepicker({
onSelect: function (date, args) {
var addYears = parseInt($('#contract').val());
var t = date.split('/');
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
$('#end').datepicker("setDate", fin);
}
});
JSFiddle

Categories

Resources