I have two input field for the time start and time end and there is another field for the difference which is the Call Duration. I want the result on the field to be in this format = 00:21:03
<div class="inline_divider">
<label for="form_qa_startcall" class="qaw_form_label3">Start of Call</label>
<input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_endcall" class="qaw_form_label3">End of Call</label>
<input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_callduration" class="qaw_form_label3">Call Duration</label>
<input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8">
</div>
I am having a hardtime getting the result due to the "AM/PM" formatting.
I have found a similar question like this but he is using "momentjs". As much as possible, I don't want to use any plugins, just a plain javascript or from jquery will do. This is the code I got working, I am getting the result (0:21:3) but I need it to be two digits for hours, minutes, and seconds (00:21:03).
$("#form_qa_endcall").on('keyup',function(){
var callStart = $('#form_qa_startcall').val();
var callEnd = $('#form_qa_endcall').val();
var timeStart = new Date("01/01/2007 " + callStart);
var timeEnd = new Date("01/01/2007 " + callEnd);
function datediff(fromDate,toDate,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
fromDate = new Date(fromDate);
toDate = new Date(toDate);
var timediff = toDate - fromDate;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return toDate.getFullYear() - fromDate.getFullYear();
case "months": return (
( toDate.getFullYear() * 12 + toDate.getMonth() )
-
( fromDate.getFullYear() * 12 + fromDate.getMonth() )
);
case "weeks" : return Math.floor(timediff / week);
case "days" : return Math.floor(timediff / day);
case "hours" : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}
var seco = datediff(timeStart, timeEnd, 'seconds') % 60;
var minu = datediff(timeStart, timeEnd, 'minutes') % 60;
var hour = datediff(timeStart, timeEnd, 'hours');
$('#form_qa_callduration').val(hour + ":" + minu + ":" + seco);
});
You could use this code:
function diff(a, b) {
function toTime(a) {
return Date.parse('1970-01-01 ' + a.substr(0,8)) / 1000
+ (a.includes('PM') && (12*60*60));
}
var d = toTime(b) - toTime(a);
return d >= 0 ? new Date(0,0,0,0,0,d).toTimeString().substr(0,8) : '';
}
$('.qaw_form_input3').on('input', function () {
$('#form_qa_callduration').val(
diff($('#form_qa_startcall').val(), $('#form_qa_endcall').val()));
}).click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inline_divider">
<label for="form_qa_startcall" class="qaw_form_label3">Start of Call</label>
<input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_endcall" class="qaw_form_label3">End of Call</label>
<input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_callduration" class="qaw_form_label3">Call Duration</label>
<input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8" readonly>
</div>
As the duration will be updated by changes to the other two input values, it would be a good idea to make the duration input read-only, by adding the readonly attribute.
Assuming you get it as strings, you can roughly do the following.
var str1 = "11:31:51 AM";
var str2 = "11:52:54 AM";
str1 = str1.split(':');
str2 = str2.split(':');
if(str1[2].split(' ').pop() != str2[2].split(' ').pop()) { // one is AM other is PM
str1[0] = parseInt(str1[0])+12;
}
var finalStr = m(str1[0], str2[0])+":"+m(str1[1], str2[1])+":"+m(str1[2], str2[2]);
console.log(finalStr);
function m(n1,n2) {
return Math.abs(parseInt(n1)-parseInt(n2));
}
Related
I am developing a web page where the Months will be calculated after entering the Date from the Input Field.
I want to take the value of "diffMonthsGlobe" to another function where this calculated value is going to the database.
But as I have seen few answers in StackOverflow and try to do the same but still in my case it is not possible
var diffMonthsGlobe;
function getValue() {
// Getting Values......
const startDate = document.getElementById("startDate").value;
const endDate = document.getElementById("endDate").value;
// Calculating Time Period.......
const date1 = new Date(endDate);
const date2 = new Date(startDate);
var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
diffMonth /= 60 * 60 * 24 * 7 * 4;
diffMonths = Math.abs(Math.round(diffMonth));
diffMonthsGlobe = diffMonths;
// Printing Values......
console.log(startDate);
console.log(endDate);
console.log(diffMonths + " Months");
return diffMonthsGlobe;
}
getValue();
console.log(diffMonthsGlobe + " Months");
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required onchange="getValue()" />
<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required onchange="getValue()" />
Use a form so the required works
Use the submit event to get the value and send to server
const getValue = function() {
// Getting Values......
const startDate = document.getElementById("startDate").value;
const endDate = document.getElementById("endDate").value;
// Calculating Time Period.......
const date1 = new Date(endDate);
const date2 = new Date(startDate);
var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
diffMonth /= 60 * 60 * 24 * 7 * 4;
diffMonths = Math.abs(Math.round(diffMonth));
diffMonthsGlobe = diffMonths;
// Printing Values......
console.log(startDate);
console.log(endDate);
return diffMonthsGlobe;
}
window.addEventListener("load", function() { // page load
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const monthDiff = getValue();
console.log(monthDiff + " Months");
// here you can fetch or otherwisde ajax to server
})
})
<form id="myForm">
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required />
<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required />
<input type="submit" />
</form>
The time are selected by the user, after the user have select both times, the duration checkbox should auto calculate the duration of the time and display the duration in the duration textarea. Please have a look on my code... Thank You. I have put an alert to test, and I still can't get the duration in the alert.
$(document).ready(function() {
var stime = document.querySelector("#FromTime"),
etime = document.querySelector("#ToTime"),
duration = document.querySelector("#duration");
stime.onchange = etime.onchange = function() {
if (!stime.value || !etime.value) {
return;
}
var sTime = stime.value.split(":"),
eTime = etime.value.split(":"),
minutes = (eTime[0] * 60 + +eTime[1]) - (sTime[0] * 60 + +sTime[1]),
hours = Math.floor(minutes / 60);
if (minutes < 1) {
return duration.innerHTML = "The ending time must be bigger than the starting time";
}
duration.innerHTML = `Duration: ${hours} hours and ${minutes % 60} minutes`
};
});
<div class="input-field col m6 s12">
<label for="FromTime">From Time : </label></br>
</br>
<input type="time" name="FromTime" id="FromTime" autocomplete="off" required>
</div>
<div class="input-field col m6 s12">
<label for="ToTime">To Time : </label></br>
</br>
<input type="time" name="ToTime" id="ToTime" autocomplete="off" required>
</div>
<div class="input-field col s12">
<label for="duration" name="duration" id="duration">Duration (Hour): </label></br>
</br>
<input type="text" name="duration" id="duration" style="width:70px; height:35px;" required>
</div>
Your code has a few inconsistencies, Try the below, put the duration calculation into a single function and assign a var to the elements.
Plus you need to set the id to the duration INPUT element not the LABEL.
$(document).ready(function(){
var fromEl = document.getElementById('FromTime');
var toEl = document.getElementById('ToTime');
var durationEl = document.getElementById('duration');
$(fromEl).change(function() {
toEl.min = fromEl.value;
updateDuration();
})
$(toEl).change(updateDuration);
function updateDuration() {
if (!fromEl.value || !toEl.value) return;
var start = new Date (fromEl.value);
var end = new Date (toEl.value);
var durationInMilliseconds = end.getTime() - start.getTime();
var durationInHours = durationInMilliseconds / (1000 * 60 * 60);
durationEl.value = durationInHours + ' hours';
}
});
<div class="input-field col s12">
<label for="duration" name="duration" >Duration (Hour): </label></br></br>
<input type="number" name="duration" id="duration" required>
</div>
Here I made this for you
var stime = document.querySelector("#start-time"),
etime = document.querySelector("#end-time"),
duration = document.querySelector("p");
stime.onchange = etime.onchange = function() {
if(!stime.value || !etime.value) {
return;
}
var sTime = stime.value.split(":"),
eTime = etime.value.split(":");
eTime[0] = eTime[0] == 0 ? 12 : eTime[0] == 12 ? 24 : eTime[0];
sTime[0] = sTime[0] == 0 ? 12 : sTime[0] == 12 ? 24 : sTime[0];
var minutes = (eTime[0] * 60 + +eTime[1]) - (sTime[0] * 60 + +sTime[1]),
hours = Math.floor(minutes / 60);
if(minutes < 1) {
duration.innerHTML = "";
return alert("The ending time must be bigger than the starting time");
}
duration.innerHTML = `Duration: ${hours} hours and ${minutes % 60} minutes`
};
<label>From time:</label>
<input type="time" id="start-time">
<label>To time:</label>
<input type="time" id="end-time">
<p></p>
can you please help me with someone with the data boxes?
I have two data boxes.
I would need to somehow create a condition in PHP or JavaScript so that the date2 field is always higher than date1.
If the condition were violated, the date2 field would be automatically set to the same date as in date1.
<div class="form-group">
<input type="date" class="form-control" onchange="vypocet();ubytko_single();ubytko_double();" onkeydown="return false" id="datumprijezdu" name="datumprijezdu" min="<?php echo (new DateTime())->format('Y-m-d'); ?>" value="<?php echo (new DateTime())->format('Y-m-d'); ?>">
<label class="form-control-placeholder" for="datumprijezdu">Datum příjezdu</label>
</div>
<div class="form-group">
<input type="date" class="form-control" onchange="DateCheck();vypocet();ubytko_single();ubytko_double();" onkeydown="return false" id="datumodjezdu" name="datumodjezdu" value="<?php echo (new DateTime('tomorrow'))->format('Y-m-d'); ?>" min="<?php echo (new DateTime('tomorrow'))->format('Y-m-d'); ?>">
<label class="form-control-placeholder" for="datumodjezdu">Datum odjezdu</label>
</div>
JS
function vypocet() {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// test it
var x = document.getElementById("datumprijezdu");
var datumprijezdu = x.value;
var y = document.getElementById("datumodjezdu");
var datumodjezdu = y.value;
const a = new Date(datumprijezdu);
b = new Date(datumodjezdu),
pocet_dnu = dateDiffInDays(a, b);
document.getElementById("demo").innerHTML = pocet_dnu;
}
function ubytko_single() {
var ubytko_single_vysledek=0;
var ubytko_single_vysledek = pocet_dnu * 1980;
document.getElementById("ubytko_single_vysledek").innerHTML = ubytko_single_vysledek + "CZK při možnosti single";
}
function ubytko_double() {
var ubytko_double_vysledek=0;
var ubytko_double_vysledek = pocet_dnu * 2260;
document.getElementById("ubytko_double_vysledek").innerHTML = ubytko_double_vysledek + "CZK při možnosti double";
}
I tried searching on the internet, but the scripts found didn't work for me: /
Here is a basic implementation that you can use. :)
If you have details, I can edit my answer.
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
function dateChecker()
{
if (date1.valueAsDate > date2.valueAsDate)
{
date2.value = date1.value;
} else
{
console.log("Dates are fine");
}
}
<input type="date" id="date1">Date 1</input>
<br>
<input type="date" id="date2">Date 2</input>
<br>
<button id="submit" onClick="dateChecker()">Check Dates</button>
I have written condition on checking date and if lead time is less than 4 hours, show error message and do not allow further action to happen. In Android mobile and website it is working fine.
In Iphone safari browser it doesnt show my message and doesnot return false and continues to perform next action. What is wrong with my code
function validate_form() {
var mytext = "";
document.getElementById("mytext").innerHTML = "";
if ($("#pickup_time").val().trim() !== "") {
var inputDate = new Date($("#pickup_time").val().trim());
var todaysDate = new Date();
if (inputDate.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0)) {
var pickup_time = $("#pickup_time").val().trim();
var pickup_min = pickup_time.substr(pickup_time.length - 2);
pickup_time = pickup_time.substr(pickup_time.length - 5);
pickup_time = pickup_time.substr(0, 2);
var date = new Date();
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
hours = hours + 4;
if (pickup_time === hours) {
if (pickup_min >= minutes) {
return true;
} else {
document.getElementById("mytext").innerHTML = "Minimum lead time required is 4Hrs to schedule a Car!";
return false;
}
} else if (pickup_time < hours) {
document.getElementById("mytext").innerHTML = "Minimum lead time required is 4Hrs to schedule a Car!";
return false;
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="success.html" method="post" class="chafviews" id="booknow" onsubmit="return validate_form(event)">
<div class="pickCont">
<input type="text" class="textField pick_datepicker" value="" name="pickup_time" id="pickup_time" placeholder="Select start date" />
<div class="fieldLable">Pickup Date and Time</div>
</div>
<div class="pickCont">
<input type="text" class="textField drop_datepicker" value="" name="dropoff_time" id="dropoff_time" placeholder="Select end date" />
<div class="fieldLable">Drop-off Date and Time</div>
</div>
<p id="mytext" style="color: red; margin-top: 50px; font-size: 13px;"></p>
<input type="submit" class="selfBook" value="Proceed" />
</form>
I need to have the value from a datepicker to a part of a variable. The value from the datepicker must be inserted instead of getAge("02/20/2017") in the this code. the date has to be changed when datepicker is used, then "leeftijd" chages as well of course
function getAge(dateString) {
var birthdate = new Date(dateString).getTime();
var now = new Date().getTime();
var n = (now - birthdate) / 1000;
if (n < 604800) { // less than a month
var week_n = Math.abs(n / 604800).toFixed(2);
return week_n;
} else if (n < 63113852) { // less than 24 months
var month_n = Math.abs(n / 2629743).toFixed(2);
return month_n;
}
}
var age = getAge("02/20/2017");
document.getElementById("age").value = age;
<form name="id">
<input id="age" class="appTextfield" type="text" name="element1" placeholder="age" value="">
<input id="weight" class="appTextfield" type="text" name="element2" placeholder="weight" value="">
<p>Date: <input type="date" id="datepicker" size="30" onchange="getAge()"></p>
</form>
I tried lots of things but i can't get it to work... i must be doing something wrong. Any solutions to get it working?
This code will help you
function getAge(dateString) {
var birthdate = new Date(dateString).getTime();
var now = new Date().getTime();
var n = (now - birthdate) / 1000;
if (n < 604800) { // less than a month
var week_n = Math.abs(n / 604800).toFixed(2);
return week_n;
} else if (n < 63113852) { // less than 24 months
var month_n = Math.abs(n / 2629743).toFixed(2);
return month_n;
}
}
function calculateAge(dateString) {
var age = getAge(dateString);
document.getElementById("age").value = age;
}
<form name="id">
<input id="age" class="appTextfield" type="text" name="element1" placeholder="age" value="">
<input id="weight" class="appTextfield" type="text" name="element2" placeholder="weight" value="">
<p>Date: <input type="date" id="datepicker" size="30" onchange="calculateAge(this.value)"></p>
</form>