comparing current time with input time in javascript - javascript

From the following html and javascript code i hope to compare the input time with current time! If the input time is less than 2 hours i want to print "Less time" in the label and if its more than 2 hours i want to print "sufficient time" in the label!
function test(){
var element = document.getElementById("time").value;
var d = new Date();
var n = d.getTime();
if(element-n>2){
document.getElementById("check").innerHTML="sufficient time";
}
else{
document.getElementById("check").innerHTML="Less time";
}
}
<html>
<body>
<form>
<span>Time</span>
<input type="time" id="time">
<input type="button" value="CHECK" onclick="test();"> <br>
<label id="check"></label>
<input class="button" type=reset name=reset value=Cancel>
</form>
</body>
</html>
when i evaluate this i always get less time! How can i correct mycode?

Working example of your code
function test() {
var element = document.getElementById("time").value;
if (element == "") {
alert("Please Enter Time");
return false;
}
else {
// get system local time
var d = new Date();
var m = d.getMinutes();
var h = d.getHours();
if(h == '0') {h = 24}
var currentTime = h+"."+m;
console.log(currentTime);
// get input time
var time = element.split(":");
var hour = time[0];
if(hour == '00') {hour = 24}
var min = time[1];
var inputTime = hour+"."+min;
console.log(inputTime);
var totalTime = currentTime - inputTime;
console.log(totalTime);
if ((Math.abs(totalTime)) > 2) {
document.getElementById("check").innerHTML = "sufficient time";
}
else {
document.getElementById("check").innerHTML = "Less time";
}
}
}
<html>
<body>
<form>
<span>Time</span>
<input type="time" id="time" required>
<input type="button" value="CHECK" onclick="return test();">
<br>
<label id="check"></label>
<input class="button" type=reset name=reset value=Cancel>
</form>
</body>
</html>

You are not considering that input value in your field has to be parsed to a Date value to be of any use in calculation:
function test(){
var timeNow = new Date();
var tm = document.getElementById("time");
var timeParts = tm.split(":");
var inputTime = new Date(timeNow.getYear() , timeNow.getMonth() , timeNow.getDate() , parseInt(timeParts[0]), parseInt(timeParts[1]), 0, 0);
var diff = Math.abs(timeNow.getTime() - inputTime.getTime());
if( diff > 2*60*60*1000 )
document.getElementById("check").innerHTML="sufficient time";
else
document.getElementById("check").innerHTML="Less time";
}
I am assuming you are checking for two hours before or after the current time. If not, feel free to remove the Math.abs and use accordingly.

This is essentially a type mismatch. You are comparing a timestamp to a time string. The getTime() returns a timestamp that specifies a time on a particular date, whereas the time string is just a string such as 02:02 which doesn't specify a date.
You will need to collect date and time from inputs, then construct a Date object from the input, then compare two getTime() results. That way you will be comparing two timestamps.
It is important that the input includes the date because of what happens around midnight. If the current time is 23:30 and the input time is 01:15, how will your code know whether the user meant 1:15 tomorrow morning?

getTime() returns milliseconds, so to get two hours, simply multiply 1000 * 60 * 60 to get one hour in milliseconds.
element will contain a string, like "12:30" and must be converted, this one might help you further:
Convert string to time JavaScript (h:m)
Hope it helps.

Related

asp:textbox hour difference with Javascript "onchange"

I need some help here, I have three <asp:TextBox> in my form and I need to calculate the time difference between 2 of them (and set the difference value on the third).
I have done it with PostBack and it's working fine, but I want to do it from client side (no PostBack needed). That's why I want to know if there is a way to make the calculation and show the value in the third TextBox with javascript.
Some times I will need to calculate the time difference between 2 different dates. But I can't set the "Date" inside the TextBox.
The Format I need is "HH:mm".
Could somebody help me with this?
EDIT (Code addition):
ASPX:
<td>
<asp:TextBox ID="TBStart1" runat="server" Width="50px"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TBEnd1" runat="server" Width="50px" AutoPostBack="true"></asp:TextBox>
</td>
<td>
<asp:TextBox ID="TBDuration1" runat="server" Width="50px"></asp:TextBox>
</td>
C#:
if (IsPostBack)
{
//CHECK IF THE FIELD IS NOT BLANK. IF IT'S BLANK, THE PROCESS WILL NOT START.
if (TBEnd1.Text != "")
{
DateTime veinticuatro1 = DateTime.ParseExact("23:59", "HH:mm", CultureInfo.InvariantCulture);
DateTime unminuto1 = DateTime.ParseExact("00:01", "HH:mm", CultureInfo.InvariantCulture);
DateTime inicio1;
inicio1 = new DateTime();
inicio1 = DateTime.ParseExact(TBStart1.Text, "HH:mm", CultureInfo.InvariantCulture);
DateTime fin1;
fin1 = new DateTime();
fin1 = DateTime.ParseExact(TBEnd1.Text, "HH:mm", CultureInfo.InvariantCulture);
//CHECK IF THE END TIME IS LOWER THAN THE START TIME. THIS MEANS THAT THE INTERVAL IS BETWEEN TWO DIFFERENT DATES (EXAMPLE: 23:50 TO 01:30)
if (fin1 < inicio1)
{
TimeSpan diferencia1 = fin1.Subtract(inicio1);
DateTime duracionveintitres1 = veinticuatro1.Add(diferencia1);
DateTime duracionfinal1 = duracionveintitres1.AddMinutes(1);
string dife1 = duracionfinal1.ToString("HH:mm");
TBDuration1.Text = dife1;
TBDuration1.Focus();
}
else
{
TimeSpan diferencia1 = fin1.Subtract(inicio1);
DateTime diferenciadt1 = DateTime.ParseExact(diferencia1.ToString(), "HH:mm:ss", null);
string dife1 = diferenciadt1.ToString("HH:mm");
TBDuration1.Text = dife1;
TBDuration1.Focus();
}
}
Some of the field names are in Spanish (diferencia, duracionveintitres, etc). Sorry for that.
it should be something similar to :
$('#TBEnd1').on('change',function()
{
var start_time = $('#TBStart1').val();
var end_time = $('#TBEnd1').val();
var diff = new Date(end_time) - new Date( start_time);
$('#TBDuration1').val(diff);
}
Finally, I found a solution for this.
I had to change my <asp.TextBox> to <input/>. I found the script in this URL:
https://www.linuxito.com/programacion/483-como-restar-horas-en-javascript
Here is the code:
SCRIPT:
function HourDifference() {
start = document.getElementById("start").value;
end = document.getElementById("end").value;
startMinutes = parseInt(start.substr(3, 2));
startHours = parseInt(start.substr(0, 2));
endMinutes = parseInt(end.substr(3, 2));
endHours = parseInt(end.substr(0, 2));
minutesDiff = endMinutes - startMinutes;
hoursDiff = endHours - startHours;
if (minutesDiff < 0) {
hoursDiff --;
minutesDiff = 60 + minutesDiff;
}
if (minutesDiff < 10) {
minutesDiff = "0" + minutesDiff;
}
if (hoursDiff < 0) {
hoursDiff = 24 + hoursDiff;
}
hours = hoursDiff.toString();
minutes = minutesDiff.toString();
if (hours.length < 2) {
hours = "0" + hours;
}
if (minutes.length < 2) {
minutes = minutes + "0";
}
document.getElementById("difference").value = hours + ":" + minutes;
}
HTML:
<p><input type="text" id="start" value=""/></p>
<p><input type="text" id="end" value="" onchange="HourDifference();" /></p>
<p><input type="text" id="difference" value="" /></p>
This is working ok.
Important:
The input format should be "HH:mm" (if 1:00 am, is 01:00; if 1:00 pm, is 13:00).
The below code will obtain a datetime in text format and find the difference in hours and minutes. I hope this will meet your requirements or at least push you on the right tracks.
HTML
<div id="textBoxOne">
2016-09-20 20:00:00
</div>
<div id="textBoxTwo">
2016-09-23 20:31:00
</div>
<div id="ShowTimeBetweenDates">
</div>
Javascript
var dateOne = document.getElementById("textBoxOne").innerHTML;
var dateTwo = document.getElementById("textBoxTwo").innerHTML;
var diff = (new Date(dateOne) - new Date(dateTwo))
var totalHours = Math.floor(Math.abs(diff/ 3600 / 1000));
var totalMinutes = Math.abs(((diff % 86400000) % 3600000) / 60000);
var showTimeDiff = document.getElementById("ShowTimeBetweenDates");
showTimeDiff.innerHTML = "Time Diff : " + totalHours + " : " + totalMinutes;
result
2016-09-20 20:00:00
2016-09-23 20:31:00
Time Diff : 72 : 31
Fiddle Here
Recommendations
Instead of parsing it like this and using a text box Jquery provides "jquery ui date parser" a simple way to obtain a date object, you can use a date picker with this. Check it out found here
hope this helps, best of luck

Javascript Calculate Time including over night

I have create code for calculating between 2 time which result in minutes.
It works fine if no overnight hour (example: 10:00 - 12:00, 14:00 - 16:00) the problem comes when I fill it with 23:00 and 01:00 (11 pm to 1 am), it return minus and count backward. You can see my code at snippet below.
Anyone know how to count it normally if there's an overnight? Or it's not possible if there's no date?
function parseTime(s) {
var c = s.split(':');
return (parseInt(c[0]) * 60) + parseInt(c[1]);
}
function getTotalMin(x)
{
var awal = document.getElementById("awaljkab").value;
var akhir = document.getElementById("akhirjkab").value;
var selisih = parseTime(akhir) - parseTime(awal);
x.value = String(selisih);
}
<!-- input clock as HH:mm ; example: 10:00 -->
<input type="text" class="form-control timepicker" name="startjkab" id="awaljkab" />
<input type="text" class="form-control timepicker" name="finishjkab" id="akhirjkab" />
<input type="text" class="form-control" name="lamajkab" onfocus="getTotalMin(this);" readonly="readonly" />
Before calculating selisih you should check if the second hour is smaller than the first one:
if (akhir < awal) akhir += 24 * 60;
That way you ensure that akhir represents the following day. After that, you can calculate selih the way you did.
You can simply add 24 hours to second value if it is less than first one
var to = parseTime(akhir);
var from = parseTime(awal);
var selisih;
if (to < from)
{
selisih = 24*60 + to - from;
} else {
selisih = to - from;
}
http://jsfiddle.net/Lse3sk44/1/

Troubles with getDay in Javascript

Hi this seems simple enough but it's not working! I am trying to take two Epoch numbers and calculate the day of the week in a loop for that current day. I need this because I want to not count the days that are on the weekend (i.e. 0 or 6).
<!DOCTYPE html>
<html>
<body>
<p>Click the button to display todays day of the week.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var oneDay = 86400;
var days = 0;
var currDay = 0;
//var d = new Date();
// get the start time in Epoch
var dayTime = 1425531600 //from the user selection
var endTime = 1425960000
//while our dayTime is less than the end time,
//loop through the days and count them.
while (dayTime < endTime) {
// advance one day
dayTime = dayTime + oneDay;
document.write("out:"+dayTime+"<br>")
//turn the new time in Epoch into a date
var d = new Date(dayTime);
document.write("out:"+d.getDay()+"<br>")
}
}
</script>
</body>
</html>
The output looks like this:
out:1425618000
out:6
out:1425704400
out:6
out:1425790800
out:6
out:1425877200
out:6
out:1425963600
out:6
Why am I ALWAYS getting '6' for each Epoch? Something wrong with my Epoch values? Note, it's 5 days so each day is 86400 long.
I copied the code into this page to test it:
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_getday
In new Date(x), x needs to be in unixEpoch format (milliseconds) - or other formats. To solve your problem, just multiply all your values by 1000:
window.onload = function() {
var oneDay = 86400000;
var days = 0;
var currDay = 0;
//var d = new Date();
// get the start time in Epoch
var dayTime = 1425531600000 //from the user selection
var endTime = 1425960000000
//while our dayTime is less than the end time,
//loop through the days and count them.
while (dayTime < endTime) {
// advance one day
dayTime = dayTime + oneDay;
document.body.insertAdjacentHTML('beforeend',"out:" + dayTime + "<br>")
//turn the new time in Epoch into a date
var d = new Date(dayTime);
document.body.insertAdjacentHTML('beforeend',"out:" + d.getDay() + "<br>")
}
}

How to compare dates - JavaScript/ASP Classic [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript to compare two dates, from strings, begin <= end
Beginner. I have a HTML form with two date fields the user fills in either manually or by a calendar picker. Start Date and End Date. Before the form can be submitted I want to check to make sure the End Date entered is >= the Start Date entered. Using Dreamweaver. Any help with this is greatly appreciated. Thank you
Dates comparison:
function compareDates(date1, date2) {
var delta = date1.getTime() - date2.getTime();
if(delta == 0) {
return 0;
}
return delta > 0 ? 1 : -1;
}
Dates difference:
var startDate = new Date(),
endDate,
delta;
setTimeout(function() {
endDate = new Date();
delta = endDate.getTime() - startDate.getTime();
alert(delta + ' ms');
}, 1000);​
DEMO
Documentation
Try something like this (here is the Fiddle)
<script type="text/javascript">
function test(){
var dt1 = new Date(""+document.getElementById("dt1").value);
var dt2 = new Date(document.getElementById("dt2").value);
alert(dt2 > dt1);
}
</script>
<input id="dt1" type="text" value="09/25/2012"/>
<input id="dt2" type="text" value="09/24/2012"/>
<input id="btn" type="button" value="test" onclick="test()"/>

I want to validate when date and time selected is past current date and time

I have two readonly textboxes, one textbox is linked with the jquery datepicker and the other textbox is linked with the timepicker jquery. Now the great thing about the jquery datepicker is that I can range my dates so that the user cannot select any dates before the current date. But the Jquery timepicker cannot be ranged so the time is before the current time.
Because of this there is a possbile chance that the user can select the current date but a time before the current time. Obviously this means the time chosen has passed the current time of the current day which I don't want happening. So a validation is needed where if date textbox and time textbox is past the current date and time, then a message is displayed stating "The Date and Time you have selected is before the Current Date and Time" else if time and date together is past current date and time then display "".
How can I do this. Below is my best attempt at it but I couldn't get it to work.
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Create a Session</title>
<script type="text/javascript">
function validation() {
var dateTextO = document.getElementById("datepicker");
var timeTextO = document.getElementById("timepicker");
var errDateTimeMsgO = document.getElementById("dateTimeAlert")
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
if (hours < 10){
hours = "0" + hours
}
if((dateTextO < currentDate) && (timeTextO < currentTime)){
errDateTimeMsgO.innerHTML = "The Date and Time you have selected is before the Current Date and Time";
} else {
errDateTimeMsgO.innerHTML = "";
}
}
</script>
</head>
<body>
<form action="create_session.php" method="post" name="sessionform">
<p><strong>4: Date:</strong> <input type="text" id="datepicker" readonly="readonly"></p>
<p><strong>5: Time:</strong> <input type="text" id="timepicker" readonly="readonly"><span class="timepicker_button_trigger"><img src="Images/clock.gif" alt="Decrease" /></span></p>
<div id="dateTimeAlert"></div>
</form>
</body>
actually the date generated by new Date() is something like this
Wed Jul 20 2011 19:09:46 GMT+0530 (IST)
but your datepicker time maybe something like this
28-07-2011
those are in two different formats . so you can not comapare , so you have to get those to one format
var checkindatestr = document.getElementById("datepicker");
var dateParts = checkindatestr.split("-");
var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = new Date();
var difference = now - checkindate;
you can find difference of the 2 days this way .
i ll find a way and tell you how to compare 2 times......... :D
UPDATE
var checkindatestr = document.getElementById("datepicker");
var dateParts = checkindatestr.split("-");
var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var nowdate = new Date();
var differenceDate = parseInt(nowdate) - parseInt(checkindate);
var checkintimestr = document.getElementById("timepicker");
var timeParts = checkindatestr.split(":");
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if(( differenceDate >= 0) && (parseInt(hours) >= parseInt(timeParts[0])) && (parseInt(minutes) > parseInt(timeParts[1]) )){
errDateTimeMsgO.innerHTML = "The Date and Time you have selected is before the Current Date and Time";
} else {
errDateTimeMsgO.innerHTML = "";
}
}

Categories