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

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()"/>

Related

How do I calculate dates and show the remaining dates with an input fied?

I would like to come to a code that show is a certain date is still valid and for how long.
The code I've come up with so far can check if the date is not in the future. But I'm unable to how if the date is still valid or not.
Can someone help me?
function TheorieFunction() {
var startDate = new Date(document.getElementById('DateTheorie').value);
var today = new Date();
if (startDate.getTime() > today.getTime()) {
alert("Error: Given date is in the future");
}
if (startDate.getTime() > today.get(Calendar.YEAR) - 3) {
document.getElementById("Theorietxt").innerHTML = "Your theorie is still valid for" + today.getTime() - startDate.getTime()
"days";
} else {
document.getElementById("Theorietxt").innerHTML = "Your theorie is invalid";
}
}
Date theorie exam: <input type="date" id="DateTheorie" value="2017-01-01">
<span class="validity"></span>
<button id=Btntheorie onclick="TheorieFunction()">Check</button>
<p id="Theorietxt"></p>
Are you looking for a solution like this? Making use of date difference function from this post
Edit: i have used only basic year difference calculation like 356 days per year. If you want the exact year difference you need to go for moment.js difference function
You can find the implementation using moment js in this fiddle
function TheorieFunction() {
var startDate = new Date(document.getElementById('DateTheorie').value);
var today = new Date();
if (startDate.getTime() > today.getTime()) {
alert("Error: Given date is in the future");
return;
}
if(startDate.valueOf() !== NaN) {
const oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
const diffDays = Math.round(Math.abs((today - startDate) / oneDay));
if (diffDays < 3 * 365) {
document.getElementById("Theorietxt").innerHTML="Your theorie is still valid for" + (diffDays) + "days";
}
else {
document.getElementById("Theorietxt").innerHTML="Your theorie is invalid";
}
} else {
alert('In Valid Date selected');
}
}
Date theorie exam: <input type="date" id="DateTheorie" value="2020-01-01" />
<span class="validity"></span>
<button id="Btntheorie" onclick="TheorieFunction()">Check</button>
<p id="Theorietxt"></p>

Disable button if input date is lesser than 4 months

I want to disable the next button when the input date is lesser than 4 months. Get the current date and check if the current date is lesser than 4 months. If it's lesser disable the next button and give an alert.
I tried it with an alert button to test the datepicker, but that didn't work:
jQuery(document).ready(function($) {
$('#input_18_104').datepicker({
onSelect: function() {
var date = $(this).datepicker('getDate');
var today = new Date();
if ((new Date(today.getFullYear(), today.getMonth(), today.getDate() + 120)) < date) {
//Do somthing here..
alert(123);
}
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<input name="input_104" id="input_18_104" type="text" class="datepicker medium mdy datepicker_no_icon hasDatepicker" tabindex="72" placeholder="Date?"> Next button:
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">
Your actual condition is wrong today.getDate()+120 will give you a number higher than 120 which will lead to a wrong date then your comparison won't be always correct.
You need to compare the month values respectively, this is how you could do it:
$(document).ready(function () {
$('#input_18_104').datepicker()
.on("input change", function (e) {
var date = $(this).datepicker('getDate');
var today = new Date();
if ((today.getMonth() + 11) - (date.getMonth() + 11) > 4) {
alert("The date is wrong");
} else if (((today.getMonth() + 11) - (date.getMonth() + 11) == 4) && (today.getDate() > date.getDate())) {
alert("The date is wrong");
} else {
console.log("Date is fine");
}
});
});
Explanataion:
We used date.getMonth() + 11 to make sure we don't get a negative
value, so we added 11 to the 2 months values, so it won't affect
the test.
Then we check if the difference between these two values isn't higher than 4, so the choosen date is fine.
Demo:
$(document).ready(function() {
$('#input_18_104').datepicker()
.on("input change", function(e) {
var date = $(this).datepicker('getDate');
var today = new Date();
if ((today.getMonth() + 11) - (date.getMonth() + 11) > 4) {
alert("The date is wrong");
} else if (((today.getMonth() + 11) - (date.getMonth() + 11) == 4) && (today.getDate() > date.getDate())) {
alert("The date is wrong");
} else {
console.log("Date is fine");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<input name="input_104" id="input_18_104" type="text" class="datepicker medium mdy datepicker_no_icon hasDatepicker" tabindex="72" placeholder="Date?"> Next button:
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">
The following approach will work
jQuery(document).ready(function($) {
$("#input_18_104").datepicker({
dateFormat: 'dd/mm/yy'}).on("changeDate", function (e) {
alert("Working");});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.css" rel="stylesheet" />
<input name="input_104" id="input_18_104" type="text" class="datepicker medium mdy datepicker_no_icon hasDatepicker" tabindex="72" placeholder="Date?"> Next button:
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">
That is not too difficult.
new Date returns a timestamp in milliseconds. The date function is pretty smart. You can overflow the months and days and it will correct it to the date: so a value of 14 as month will actually become February or March. But you really want to stay away from day calculation or subtracting months because of leap years, 30 and 31 day count etc. Comparing time stamps is safer.
new Date(date)
Just add 4 months:
//remember month is zero based, so correct with +1 to give correct date input.
future = new Date(today.getFullyear()+"-"+(today.getMonth()+1+4)+"-"+today.getDate())
Now compare:
future < new Date(date);
When the selected date is bigger than the future 4 month date it will be more than 4 months.
Under the hood JavaScript compares timestamps which are counted in milliseconds from 1970-01-01 so whenever a timestamp is bigger than another it is in the future relative to the compared timestamp.
I would compare the dates based on their time values. That's not 100% accurate because not all months have 30 days, but ok. Here's a quick try
jQuery(document).ready(function ($) {
$('#input_18_104').datepicker({
onSelect: function(){
var date = $(this).datepicker('getDate');
var today = new Date();
var threshold = 10368000000; // 120d in ms = 4*30*24*60*60*1000
var d = today.getTime()-date.getTime();
//console.log(d, d > threshold)
// be optimistic...
$('#next_button_18_94').attr('disabled', false);
if (d < 0) {
// selected date is in the future => everything ok
return;
}
if (d > threshold) {
// oops, selected date more than 4 months in the past
$('#next_button_18_94').attr('disabled', true);
return;
}
},
});
});
#next_button_18_94[disabled]{
border: 2px solid red;
}
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<input name="input_104" id="input_18_104" type="text" tabindex="72" >
<input type="button" id="next_button_18_94" class="form_next_button button" value="Next" tabindex="76">
Assuming that "lesser than 4 months" mean means the input date is less than 4 months before today, then a simple method is to add 4 months to the input date and see if it's less than today, then enable or disable the button as required, e.g.
function checkDate(input) {
var form = input.form;
var now = new Date();
var then = parseDate(input.value);
addMonths(then, 4);
form.actionButton.disabled = now > then;
}
function parseDate(s) {
var b = s.split(/\D/)
return new Date(b[0], b[1]-1, b[2]);
}
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) date.setDate(0);
return date;
}
<form>
Date (yyyy-mm-dd)<input type="text" value="2017-01-01" name="date" onblur="checkDate(this)"><br>
<input type="button" name="actionButton" onclick="console.log(this.form.date.value)" value="Do stuff" disabled>
Use monthDiff function
jQuery(document).ready(function ($) {
$('#input_18_104').datepicker({
onSelect: function () {
var date = $(this).datepicker('getDate');
var today = new Date();
if (monthDiff(today, date) < 4) {
//Do somthing here..
alert(123);
}
},
});
});
function monthDiff(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth();
return months <= 0 ? 0 : months;
}

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

HTML5 datepicker prevent past dates [duplicate]

This question already has answers here:
Disable certain dates from html5 datepicker
(6 answers)
Closed 9 years ago.
I am working on a website for booking movie tickets. What should I set the min attribute to, to prevent past dates in the HTML5 datepicker? (I do not want to use PHP solution mentioned here.)
Is there a pure HTML5/Javascript solution for this?
When the document loads have the date input disabled. Run an onload function that inserts today's date into the min field in the required format.
function onLoad() {
var input = document.getElementById("dateField");
var today = new Date();
// Set month and day to string to add leading 0
var day = new String(today.getDate());
var mon = new String(today.getMonth()+1); //January is 0!
var yr = today.getFullYear();
if(day.length < 2) { day = "0" + day; }
if(mon.length < 2) { mon = "0" + mon; }
var date = new String( yr + '-' + mon + '-' + day );
input.disabled = false;
input.setAttribute('min', date);
}
document.addEventListener('load', onLoad, false);
<body>
<input id="dateField" type="date" disabled />
</body>
Here it is in a fiddle: http://jsfiddle.net/tj9Xh/2/
try this:
<input id="dateField" type="date"/>
var dt= new Date();
var yyyy = dt.getFullYear().toString();
var mm = (dt.getMonth()+1).toString(); // getMonth() is zero-based
var dd = dt.getDate().toString();
var min = yyyy +'-'+ (mm[1]?mm:"0"+mm[0]) +'-'+ (dd[1]?dd:"0"+dd[0]); // padding
alert(min);
$('#dateField').prop('min',min);

Categories