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.
Related
I am using this code for the validation, it works fine when using the default datepicker in html but when typing the date manually, it's not properly working. For example, when I type a start date then proceed to the endate, the year in the end date automatically reads only the first number of "2019" so you can't finish typing properly since it alerts and can't compare properly.
<input type="date" id="StartDate" />
<input type="date" id="EndDate" />
<script>
console.clear();
var startDate = document.getElementById("StartDate").value;
var endDate = document.getElementById("EndDate").value;
function compareDates() {
if ((Date.parse(endDate) <= Date.parse(startDate))) {
alert("End date should be greater than Start date");
document.getElementById("EndDate").value = "";
}
}
startDate.addEventListener('input', compareDates);
endDate.addEventListener('input', compareDates);
</script>
Any tips?
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);
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).
I'm Struggling with calculation of date time objects :(
We're getting three inputs from the user:
1. Start time of day
2. End time of day
3. Intervals between events (in minutes)
My target goal is to calculate how many events I have every day from start time to end time by the selected interval, and creating an array with the exact times of these events.
So far I'm getting the data in this way:
StartTime is a Datetime object.
EndTime is a Datetime object.
//Get start time
var HourOfStart = StartTime.getHours();
var MinuteOfStart = StartTime.getMinutes();
//Get end time
var HourOfEnd = EndTime.getHours();
var MinuteOfEnd = EndTime.getMinutes();
After calculating the differences of how many events in an hour and trying to cap the first and last events, I realised I must be doing something wrong (math is not my strong suit). Also converting to a unix timestamp got me baffled, because the events aren't starting at a round hour.
So in a nutshell, if the user enters:
Start time: 10:15
End time: 12:30
Interval: 15 minutes
I need to get the following array of event times:
10:30,10:45,11:00,11:15,11:30,11:45,12:00,12:15
Thanks!!
Here's a function that should do what you want. As suggested in the comments, just calculate the time in milliseconds and increment until you reach your stop time.
function calculate() {
var a = [];
var startValue = document.getElementById("startTime").value;
var endValue = document.getElementById("endTime").value;
var intervalValue = document.getElementById("interval").value;
var startDate = new Date("1/1/2015 " + startValue);
var endDate = new Date("1/1/2015 " + endValue);
var offset = intervalValue * 1000 * 60;
do {
startDate = new Date(startDate.getTime() + offset);
if (startDate < endDate)
a.push(startDate);
} while(startDate < endDate);
console.log(a);
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<label for="startTime">Start Time</label>
<input id="startTime" value="10:15" />
<br/>
<label for="endTime">End Time</label>
<input id="endTime" value="12:30" />
<br/>
<label for="interval">Interval</label>
<input id="interval" value="15" />
<br/>
<input type="button" onclick="calculate()" value="Calculate" />
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