How to create a condition with two inputs with date? - javascript

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>

Related

Local Variable to Global Variable in JavaScript

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>

It is possible to add an integer input with a time type input and result to a time type input?

As I mention in the title I have three input in HTML:
<input type="number" name="time" id="time">
<input type="time" name="hour_start" id="hour_start">
<input type="time" name="hour_final" id="hour_final">
and JS:
<script>
$("#time").change(function () {
var time = $('#time').val();
var start = $('#hour_start').val();
var convert = Math.floor(time/60);
var final = start + convert;
$('#hour_final').val(final);
});
</script>
The calculation is done without using a button.
Enter image description here
Javascript answser ( as you asking) :
const myForm = document.querySelector('#my-Form')
, z2 = v=>('00'+v).slice(-2) // like padStart(2.'0')
myForm.time.oninput=_=>
{
let inDate = myForm.hour_start.valueAsDate
, h_UTC = inDate.getUTCHours()
, m_UTC = inDate.getUTCMinutes()
, nTim = (h_UTC * 60) + m_UTC + myForm.time.valueAsNumber
h_UTC = Math.trunc(nTim/60) % 24
m_UTC = nTim % 60
inDate.setUTCHours(h_UTC)
inDate.setUTCMinutes(m_UTC)
myForm.hour_final.valueAsDate = inDate
}
myForm.onsubmit=e=>
{
e.prventdefault() // just for test
}
<form action="xxx" id="my-Form">
<input type="number" name="time" value="0" min="0" max="2000">
<input type="time" name="hour_start" value="13:30">
<input type="time" name="hour_final" value="13:30">
</form>

Need value of datepicker as part of variable

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>

Calculate time difference in hh:mm:ss with simple javascript/jquery

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));
}

javascript array Not Working properly

I am facing some problems arrays in php,,
<input class="form-control" placeholder="Start Time"
value="'.date("H.i").'" type="text" name="starttime[]" id="starttime"/>
</div>
<div class="col-lg-4">
<input class="form-control" name="endtime[]" id="endtime" onchange="myfunction1()" value="00.00" type="text" placeholder="End Time">
This is my ajax code and when I change end time It must be show other text box
<input class="form-control" name="kmcost" id="exkms" type="text" placeholder="Cost">
But single entry working but second entry(array) Not woeking my javascript code is here please help me..
my javascript is here..
function myfunction1()
{
var ftime = document.getElementById("starttime").value;
var etime = document.getElementById("endtime").value;
var timeanswer = etime - ftime;
var localtottme = document.getElementById("textbox3").value;
if(timeanswer > 8)
{
var totextme = timeanswer-8;
}
var exkms = document.getElementById('exkms');
exkms.value=totextme;
}
Try this:
function myfunction1()
{
// fetch value of element as string, x2
var ftime = document.getElementById("starttime").value;
var etime = document.getElementById("endtime").value;
// fetch hour as string, then convert to integer, x2
ftime = parseInt(ftime.split(':')[0]);
etime = parseInt(etime.split(':')[0]);
// calculate hour difference, initialize remainder variable to 0
var hourDifference = etime - ftime;
var eightHourRemainder = 0;
// check if hour difference is more than 8, if so then calculate remainder variable
var localtottme = document.getElementById("textbox3").value;
if(hourDifference > 8)
{
eightHourRemainder = hourDifference - 8;
}
// set element value to remainder variable
var exkms = document.getElementById('exkms');
exkms.value=eightHourRemainder;
}

Categories