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
Related
I'm using the jonthornton/jquery-timepicker and could not find the hours and minutes selected.
All I could find was a string output of the form '10:30pm'.
Can the hours and minutes be accessed directly from the control?
I imagined you would be able to do this but could not find it.
The best I've been able to do is what follows, anyone got anything better?
$('#StartTime').on('change', function (timeControl) {
var hoursString;
if (timeControl.target.value.indexOf("am") >= 0) {
hoursString = timeControl.target.value.replace("am", ":00 AM");
}
else {
hoursString = timeControl.target.value.replace("pm", ":00 PM");
}
var oneDate = new Date(Date.parse("2000-01-01 " + hoursString));
var minutes = oneDate.getMinutes();
var hours = oneDate.getHours();
console.log("Hours : " + hours + " | Minutes : " + minutes);
});
The long-standing answer would be Moment.js but it is now considered a legacy project in maintenance mode and not recommended for new projects. There are recommendations on their website for replacements, but bringing in a new dependency for this may be overkill.
The value coming in seems to follow a format which we can rely on to make parsing easy.
Format: H:MMxx
Key:
H = hour, 1-2 characters
MM = minutes, always 2 characters
xx = am or pm, always 2 characters
var timeArray = timeControl.split(':');
var meridiem = timeArray[1].substring(2, 4);
var hours = parseInt(timeArray[0]) + (meridiem === 'pm' ? 12 : 0);
var minutes = parseInt(timeArray[1].substring(0, 2));
var seconds = 0;
// Local time zone, read more: https://stackoverflow.com/a/29297375/5988852
var date = new Date();
date.setHours(hours, minutes, seconds);
// If you want UTC instead
utc = Date.UTC(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
hours,
minutes,
seconds
);
var date = new Date(utc);
I have a form with input time type. I want to set the actual hour automatically.
This Javascript works but set a fixed hour to 08:15 :
<script>
$("#myelement").val( "08:15" );
</script>
This script should get the actual hour but set an empty value to the field :
<script>
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes();
$("#myelement").val( time );
</script>
How to fix it ?
It's not displaying the time cause it's not following the 'time' format. When the time is less than 10, numbers should have a leading 0. E.g. 09:17
var date = new Date();
var hour = date.getHours();
var min = date.getMinutes();
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
var time = hour + ":" + min;
$("#myelement").val( time );
Source: https://stackoverflow.com/a/41480350/6099890
You can do it like this :
<script>
var d = new Date();
document.getElementById("myelement").innerHTML = d.toTimeString();
</script>
If you wish to stick with JQuery
<script>
var d = new Date($.now());
alert(d.getDate()+"-"+(d.getMonth() + 1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds());
</script>
See how it works :
https://jsfiddle.net/g35uxqtp/171/
The time input value needs a 24-hour format. So zero-padding the values works
const dt = new Date();
// create a zero padded time value
const time = [`${dt.getHours()}`.padStart(2, "0"),
`${dt.getMinutes()}`.padStart(2, "0")].join(":");
const inp = document.querySelector("#myelement");
// demo
setTimeout(() => inp.value = "8:15", 1000); // does not work
setTimeout(() => inp.value = "08:15", 2000); // works
setTimeout(() => inp.value = time, 4000); // works
<input type="time" id="myelement">
I have a page that shows the start date and end date like below:
As you can see the end date is always 7 days more than the start date by default. I am allowed to change the start date but how do I make sure every time I change the start date,the end date also adds up 7 days to the respective start date?
Code:
<%
String relPath = "../../../";
String currentDate = CoreUtil.parseDate(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//get current date
Calendar cal = Calendar.getInstance();
//Number of Days to add
cal.add(Calendar.DAY_OF_MONTH, 7);
String defaultDate = sdf.format(cal.getTime());
%>
Start Date: <input class="txtStartDate" style="font: 13px/1.231 Trebuchet MS;" type="text" id="txtStartDate" name="Start Date" value="<%=currentDate%>" readonly><br><br>
End Date: <input class="txtEndDate" style="font: 13px/1.231 Trebuchet MS;" type="text" id="txtEndDate" name="txtEndDate" value="<%=defaultDate%>" readonly required/>
Edit:
This is my JavaScript code:
<Script>
$('#txtStartDate').datepicker();
$('#txtEndDate').datepicker();
$('#txtStartDate').change(function(){
var interval = 7;
function convertDateString(p) { return (p < 10) ? '0' + p : p; }
var startDate = new Date($(this).val());
startDate.setDate(startDate.getDate() + interval);
$('#txtEndDate').val( startDate.getFullYear() + '/' + convertDateString(startDate.getMonth() + 1) + '/' + convertDateString(startDate.getDate()));
});
</script>
Basically whenever I change my start date, the end date should be automatically change to (start date+7 days) as well, that's all I'm trying to do. The above code should have work but it did not change my end date when I changed my start date.
This might help.
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
$('#txtStartDate').datepicker();
$('#txtEndDate').datepicker();
$('#txtStartDate').change(function(){
var interval = 7;
var startDate = new Date($(this).val());
$('#txtEndDate').val(startDate.addDays(interval));
});
You can do the calculation using a JavaScript Date object and the formatting using Strings:
// Get references to HTML elements
const startInput = document.getElementById("txtStartDate");
const endInput = document.getElementById("txtEndDate");
// Listen for changes to #txtStartDate
startInput.addEventListener("change", updateEndDate);
// Respond to changes
function updateEndDate(event){
// Calculate end date
let endDate = new Date(startInput.value);
endDate.setUTCDate(endDate.getUTCDate() + 7);
// Separate the parts of end date
let yyyy = endDate.getUTCFullYear(),
mm = endDate.getUTCMonth() + 1,
dd = endDate.getUTCDate();
// Add initial zeros if needed
if(mm < 10){mm = "0" + mm; }
if(dd < 10){dd = "0" + dd; }
// Format and display end date
endInput.value = `${yyyy}-${mm}-${dd}`;
}
<input type="date" id="txtStartDate" />
<input type="date" id="txtEndDate" />
I have three input controls in a form as,
date (which display the current date but user can select any date from a calendar)
start time(current time)
end time(start time + 30 minutes)
on page load
HTML:
Date:<input type="text" name="txtdate" id="txtdate" />
Start time:<input type="time" name="txtstart" id="txtstart" />
End time:<input type="time" name="txtend" id="txtend" />
I use jquery to get this done and the code is as follows
jquery:
$(document).ready(function() {
$("#txtdate").datepick({dateFormat:'yyyy-mm-dd',minDate: 0});
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var year1 = d.getFullYear();
var hour = d.getHours();
var mins = d.getMinutes();
var today = year1 + '/' + month + '/' + day;
$("#txtdate").val(today);
var time = hour + ":" + mins;
$("#txtstart").val(time);
var a = time.split(':');
var totmins = (+a[0])* 60 + (+a[1])+30;
var nhour = Math.floor(totmins/60);
var nmins = totmins%60;
var ntime = nhour + ":" + nmins;
$("#txtend").val(ntime);
});
in the above code it displays the current date, time and adds up 30 minutes to the current time correctly but sometimes when assigning values, the start time and end time fields don't display the time! for an example,
when current time is 12.00 AM, no value is displayed in start time and end time input fields
I don't see any error in the code but since i'm new to jquery i need to know if i had done anything wrong here (may be when assigning values) or is there another way to do this?
Note:
It should be noted that I have use HTML 5 input type time control to input start time and end time
My guess to your question is that after adding 30 minute to your Start Time, End Time is already the next day.
Take this for example.
Start Time: 23.50
Based on your calculation, +30min gives you
End Time: 24.20
24.20 is an invalid value for input[type='time']
Edit: Jacob's answer solves the problem to your flawed algorithm.
Edit 2: Modifying Jacob's answer, this will get you the endDate
var d = new Date(); //get current time.
var thirtyMinutes = 30*60*1000; //30 minutes in milliseconds
var futureDate = new Date(d.getTime() + thirtyMinutes); //current time in milliseconds + 30 minutes in milliseconds.
var endDateHour = futureDate.getHours();
var endDateMinutes = futureDate.getMinutes();
if (endDateMinutes<10) {
endDateMinutes = "0"+endDateMinutes;
}
var endDate = endDateHour + ':' + endDateMinutes;
Don't bother with this complicated "add 30 minutes" logic when you can simply use Date which is already good at date/time math.
var d = new Date();
// ...
var thirtyMinutes = 30*60*1000;
var futureDate = new Date(d.getTime() + thirtyMinutes);
var ntime = futureDate.getHours() + ':' + futureDate.getMinutes();
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 = "";
}
}