Javascript Calculate Time including over night - javascript

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/

Related

Why won't JavaScript code calculate months between two HTML date time inputs?

I'm trying to calculate the number of months between two HTML date time inputs.
This means the expected result is when the user selects 7/21/21 from the dropdown calendar as a start date and 8/21/21 as an end date then it would be one month.
My actual results are not displayed on the screen.
I didn't get any error messages so I don't know what to fix.
I tried calculating the month difference between two dates by using Date.parse().value on the start date (movein-input) and the end date (moveout-input) and calculating the time apart in milliseconds(ms), minute, hour, day, month, year, years, months, days, and hours but it did work. I found the idea on youtube (https://www.youtube.com/watch?v=Q3oiSwdGAq8) and w3schools (https://www.w3schools.com/jsref/jsref_parse.asp).
W3schools said when you display a date object in HTML, it is automatically converted to a string so I thought I could use the html date input in Date.Parse().value.
This is my JavaScript code
function calculatePrice() {
let d1 = document.getElementById("movein-input").value;
let d2 = document.getElementById("moveout-input").value;
let msBetweenD1And1970 = Date.parse(d1);
let msBetweenD2And1970 = Date.parse(d2);
let timeInMs = msBetweenD2And1970-msBetweenD1And1970;
let ms = timeInMs;
let second = 1000;
let minute = second*60;
let hour = minute*60;
let day = hour*24;
let month = day*30;
let year = day*365;
let years = Math.round(ms/year);
let months = years*12;
var t1 = "That is : "+months;
document.getElementById("m").innerHTML=t1
}
I also have the html code
<h2><span id="m">$</span></h2>
Calculate price is in the button
<button onclick="calculatePrice()">Enter</button>
You were multiplying when you needed to be dividing.
let months = Math.round(ms / 1000 / 60 / 60 / 24 / 30)
function calculatePrice() {
let d1 = document.getElementById("movein-input").value;
let d2 = document.getElementById("moveout-input").value;
let msBetweenD1And1970 = Date.parse(d1);
let msBetweenD2And1970 = Date.parse(d2);
let timeInMs = msBetweenD2And1970-msBetweenD1And1970;
let ms = timeInMs;
let months = Math.round(ms / 1000 / 60 / 60 / 24 / 30)
var t1 = `That is ${months} months`;
document.getElementById("m").textContent=t1
}
<h2><span id="m">$</span></h2>
<input type='date' id='movein-input' value='2021-03-01' />
<input type='date' id='moveout-input' value='2021-06-01' />
<button onclick='calculatePrice()'>calculate</button>

comparing current time with input time in 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.

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

How to get End time based on selected Start time and Interval?

Currently working on a project where I have to build time picker with start, end time and interval of meeting. User first pick start time for example 7:15am, then next step is to pick meeting interval that range from 5 min up to 60 min, and last step is end time that should start based on picked start time and meeting interval. So if user pick 7:30am for start time, and pick meeting interval 50 min, my end time should start at 8:20am, 9:10am, 10:00am,... all the way up to 5pm but not greater than. First problem with my current is Start Time picker, in drop down next to 12 hour value I should have PM. My code gives me AM. Second is End Time works fine if I pick meeting interval from 5 min up to 45 min, but if I pick meeting length 50 min or 55 min I'm not getting correct end time values in drop down.
HTML:
<tr>
<th>Start Time:</th>
<td>
<select name="stime" id="stime" />
<option value="">--Select start time--</option>
</select>
</td>
<br />
<th>Meeting Length:</th>
<td>
<select name="meet_leng" id="meet_leng" onClick="setEndTime()">
<option value="">--Select length--</option>
</select>
</td>
<br />
<th>End Time:</th>
<td>
<select name="etime" id="etime"/>
<option value="">--Select end time--</option>
</select>
</td>
</tr>
JavaScript:
$(function() {
for(var i=5; i <= 60; i+=5){
$('#meet_leng').append('<option value="'+i+'">'+i+' min'+'</option>');
}
for(var i=700; i<= 1700; i+=15){
var mins = i % 100;
var hours = parseInt(i/100);
if (mins > 45) {
mins = 0;
hours += 1;
i = hours * 100;
}
var standardTime = ' AM';
if(hours > 12){
standardTime = ' PM';
hours %= 13;
hours++;
}else{
hours %= 13;
}
$('#stime').append('<option value="'+i+'">'+('0' + (hours)).slice(-2)+':'+('0' +mins).slice(-2)+standardTime+'</option>');
}
});
function setEndTime(){
var meetingLength = $('#meet_leng').val();
var selectedTime = $('#stime').val();
var sum = meetingLength + selectedTime;
for(var i=sum; i <= 1700; i+=meetingLength){
var mins = i % 100;
var hours = parseInt(i/100);
if (mins > 59) {
var new_mins = mins % 60;
hours += 1;
i = (hours * 100) + new_mins;
}
$('#etime').append('<option value="'+i+'">'+i+'</option>');
}
}
Here is my working example: https://jsfiddle.net/dmilos89/rhuh6qum/22/.
If anyone can help with this problem please let me know.
basically you could look at using the Date api instead. In the bottom example, we have a startTime which can be a string,
we split it into integers
create a new Date object and set the time to the startTime
add your change in minutes
then pull out the new hour/minutes and format as you please
(i think there are ways to get this via the Date api, but i figured heavy handed was fine for the example)
https://jsfiddle.net/2fpg3rte/1/
var time = new Date();
var startTime = "12:01 PM";
var timeChange = 60; //60 minutes
var startHour = startTime.split(':')[0];
var startMin = startTime.split(':')[1].replace(/AM|PM/gi, '');
time.setHours(parseInt(startHour));
time.setMinutes(parseInt(startMin));
$("#start").html(getFormattedTime(time));
//adjusted time
time.setMinutes(time.getMinutes() + timeChange);
$("#end").html(getFormattedTime(time));
function getFormattedTime(time) {
var postfix = "AM";
var hour = time.getHours();
var min = time.getMinutes();
//format hours
if (hour > 12) {
hour = (hour - 12 === 0) ? 12 : hour - 12;
postfix = hour === 0 ? "AM" : "PM";
}
//format minutes
min = (''+min).length > 1 ? min : '0' + min;
return hour + ':' + min + ' ' + postfix;
}

jQuery set text value based on the value of a dropdown and a text value (timepicker)

I would like the set the time in a text field (timepicker) based on the values of a select menu and another timepicker text value.
The idea is that a different appointment types have different appointment lengths, and based on the appointment type and start time, I want to set the appointment end time.
<!-- Appt Type --->
<select id="ApptPurpose" name="ApptPurpose" class="form-control">
<option value="AHA">AHA</option> <!-- 60 minute appointment -->
<option value="FU">FU</option> <!-- 30 minute appointment -->
<option value="Screening">Screening</option> <!-- 30 minute appointment -->
</select>
<!-- Appt Start Time--->
<input type="text" name="ApptStartTime" id="ApptStartTime" class="Time form-control" />
<!-- Appt End Time--->
<input type="text" name="ApptEndTime" id="ApptEndTime" class="Time form-control" />
I know how to do this in C#, but I was hoping to use jQuery for this. I don't know how to do with the 2 conditions. My jQuery skills aren't very strong. Here is what I have so far.
$(function () {
var ApptPurpose = $('#ApptPurpose').val();
var ApptStartTime = $('#ApptStartTime');
var ApptEndTime = $('#ApptEndTime');
//when appt purpose changes
$("#ApptPurpose").change(function () {
// set end time
});
// or when start time changes
$("#ApptStartTime").change(function () {
// set end time
});
});
Thanks in advance for the help!
Here is what I have tried so far. I don't think that I am doing the time calculation correctly.
$(function () {
var ApptPurpose = $('#ApptPurpose').val();
var ApptStartTime = $('#ApptStartTime');
var ApptEndTime = $('#ApptEndTime');
if (ApptPurpose == "FU") {
var ApptLength = 30;
}
else if (ApptPurpose == "Screening") {
var ApptLength = 30;
}
else {
var ApptLength = 60;
}
//when appt purpose changes
$("#ApptPurpose").change(function () {
// set end time
var StartTime = $('#ApptStartTime').val().split(/:/),
ApptLengthTime = ApptLength.split(/:/);
timeDiff(StartTime[0] * 3600 + StartTime[1] * 60, ApptLengthTime[0] * 3600 + ApptLengthTime[1] * 60, $('#ApptEndTime'));
});
// or when start time changes
$("#ApptStartTime").change(function () {
// set end time
});
});
I'm not sure what you were trying to accomplish with your timeDiff calculation, but I think you're over-thinking the problem.
If you add the duration to the minutes and do a check to see if the sum is equal to or greater than 60, you can simply add an hour and subtract 60 from the minutes' sum to get the proper time. If the sum is less than 60, all you have to do is add the duration to the minutes.
function setTime() {
var ApptPurpose = $('#ApptPurpose').val(),
ApptStartTime = $('#ApptStartTime').val(),
ApptEndTime = $('#ApptEndTime'),
ApptPeriod = ApptStartTime.slice(-2), // Grab the last two characters (am or pm)
ApptLength = 0;
// Only proceed if #ApptStartTime isn't empty
if (ApptStartTime.length) {
var ApptSplit = ApptStartTime.split(/:/),
ApptStartHour = parseInt(ApptSplit[0]), // Convert the hour string to an integer
ApptStartMin = parseInt(ApptSplit[1]); // Convert the minute string to an integer
if (ApptPurpose == "FU" || ApptPurpose == "Screening") {
ApptLength = 30;
} else {
ApptLength = 60;
}
// Add the duration to the minutes. If it's equal to or more than 60..
if (ApptStartMin + ApptLength >= 60) {
++ApptStartHour; // Increment the hour by 1
// Fix the hour if it spills over 12 and change the AM/PM to match
if (ApptStartHour >= 12) {
ApptStartHour = ApptStartHour === 13 ? 1 : ApptStartHour;
ApptPeriod = ApptPeriod === 'pm' ? 'am' : 'pm';
}
ApptStartMin = ApptStartMin + ApptLength - 60; // Subtract 60 from the sum
// Make sure we always have two digits (e.g. '00' instead of '0')
ApptStartMin = ("0" + ApptStartMin).slice(-2);
// If it's less than 60...
} else {
ApptStartMin = ApptStartMin + ApptLength; // Add the duration to the minutes
}
// Rebuild the time string and plop it into #ApptEndTime
$('#ApptEndTime').val(ApptStartHour + ':' + ApptStartMin + ApptPeriod);
}
}
$('.Time').timepicker({ 'scrollDefault': 'now' });
// When #ApptPurpose changes
$("#ApptPurpose").change(function () {
setTime();
});
// or when #ApptStartTime changes
$("#ApptStartTime").change(function () {
setTime();
});
Edit: Now that we know which timepicker plugin you're using, I've updated my answer to account for AM/PM and to keep it from spitting out erroneous hours like "13:01 PM".
Updated fiddle: http://jsfiddle.net/uLgvy7qn/10/

Categories