I know how to use javascript, but i have no in depth knowledge of it. I know how I can get the date difference in days in PHP but in this case, I need javascript solution. Honestly, i don't even know if it is possible, to do this with Javascript. I guess that it is,but that is just a guess.
Here is the html that I have:
<div class="span3" id="checkin">
<span class="text-label"><i class="icon-calendar"></i>Check In</span>
<input type="text" name="checkin" value="02/08/2014">
</div>
<div class="span3" id="checkout">
<span class="text-label"><i class="icon-calendar"></i>Check Out</span>
<input type="text" name="checkout" value="04/08/2014">
</div>
Those two fields are actually bootstrap date pickers. They always come with some default values. Now, I want when user change those two values to calculate the difference between two dates (alert or console log will do, I will find my way from there).
Problem is that I have no clue where to start and how to do that calculation. Again I guess that onchange event may be a good candidate but...I have no idea how to calculate the difference.
Any help will be deeply appreciated.
Regards, John
You could first parse your string an create a JavaScript date like that:
var start = $("input[name=checkin]").val().split("/");
var end = $("input[name=checkout]").val().split("/");
var startDate = new Date(start[2], start[1]-1, start[0]);
var endDate = new Date(end[2], end[1]-1, end[0]);
Then you can simply substract the dates from each other:
endDate - startDate
That substraction will give you the time difference in milliseconds. To convert that to days, simply divide it by the number of milliseconds in a day (1000 * 60 * 60 * 24).
Now you have the difference in days. For an example, see JSFiddle.
<script type="text/javascript">
//Set the two dates
today=new Date()
var christmas=new Date(today.getFullYear(), 11, 25) //Month is 0-11 in JavaScript
if (today.getMonth()==11 && today.getDate()>25) //if Christmas has passed already
christmas.setFullYear(christmas.getFullYear()+1) //calculate next year's Christmas
//Set 1 day in milliseconds
var one_day=1000*60*60*24
//Calculate difference btw the two dates, and convert to days
document.write(Math.ceil((christmas.getTime()-today.getTime())/(one_day))+
" days left until Christmas!")
This short Javascript will display the DAY difference between today (value 1) and christmas (your value 2). Ovbioulsy these can be replaced with our two values and should then work.
Example: 146 days left until Christmas!
var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Try this . i found it from this link
Related
I would like to display the difference between two dates:
date_debut<input type="text"name="date_debut" id="datepicker">
</br>
date fin<input type="text"name="date_fin"id="datepicker2">
</br>
nombre jour <input type="text"name="nombre_jour">
</br>
I want to enter the date start and end date and affect me in the number of days - the difference of two dates.
I made a small script, but it does not work. I'm a beginner to JavaScript and I had no time to learn JavaScript.
Here is the script I have made:
$('#datepicker, #datepicker2').datepicker();
$('button').click(function () {
var start = $('#datepicker').val(),
end = $('#datepicker2').val();
var diffInDays = moment(end).diff(moment(start), 'days');
alert(diffInDays);
});
According to Comparing Datepicker Dates Javascript, use .datepicker("getDate") instead of .val() to get the date and then it should just be:
var days = (end - start) / (86400 * 1000)
So there's plenty of examples on how to calculate the time between two dates.
But in my case, I have a date X. Let's say it's today.
X has a time associate to it, e.g. 08:00 (Or what I get back from .getHours())
I need to know if the hours of X are between a start hour (say "07:00") and an end hour (say "12:00")
X will be always retrieved via getHours()
The start and end hour of the range have a fixed format (e.g. "07:00" and "12:00")
Performance is an issue, so whatever performs better is preferred (e.g. if it implies using moment, that's fine, but if a custom function would perform better, we want that)
My first approach would be, as the formats are fixed, to transform the .getHours() to a number, likewise for the range hours, and then calculate...I feel this approach my have trouble with some special cases I may not be aware of?
You could use moment-range
From docs:
You can also create a range from an ISO 8601 time interval string:
var timeInterval = "2015-01-17T09:50:04+00:00/2015-04-17T08:29:55+00:00";
var range = moment.range(timeInterval);
range.contains(X); // true if between interval
If you want to check part hours, consider converting the hours to minutes, something like the following. How will you deal with ranges that go over midnight? e.g. 23:30 to 01:30.
/* Determine if the current time is between two provided hours
** #param {string} h0 - time in format h:mm
** #param {string} h1 - time in format h:mm
** #returns {boolean} true if the current time is between or equal to h0 and h1
*/
function betweenHours(h0, h1) {
var now = new Date();
var mins = now.getHours()*60 + now.getMinutes();
return toMins(h0) <= mins && mins <= toMins(h1);
}
/* Convert hours to minutes
** #param {string} h - time in format h:mm
** #returns {number} time converted to minutes
*/
function toMins(h) {
var b = h.split(':')
return b[0]*60 + +b[1];
}
<form>
Start time (h:mm)<input name="startHours">
<br>
End time (h:mm)<input name="endHours">
<br>
<button type="button" onclick="
this.form.inRange.value = betweenHours(this.form.startHours.value, this.form.endHours.value);
">Check range</button>
<br>
Currently in range? <input name="inRange" readonly>
</form>
Are you dealing with military tine? (From 0:00 to 24:00)
getHours() returns an Integer, and if you are only interested in hours and not minutes, you can use parseInt() to turn the start and end hours into integers as well. For example, parseInt('07:00', 10) will return 7. So if you wanted to create a function to test if the current time is between two hours, it might look something like this:
function isBetweenHours(startHour, endHour)
{
var now = new Date().getHours();
return now >= parseInt(startHour, 10) && now <= parseInt(endHour, 10);
}
Then you would use it like this:
if( isBetweenHours('07:00', '12:00') ) { //some code here }
Apologies in advance for my (something less than) basic knowledge of java script.
Can someone explain in basic – but specific – terms how this script is calculating?
Here is the script:
var d = new Date(year, month, day);
var e = new Date(d.getTime() + offset * 24 * 60 * 60 * 1000);
var month_out = e.getUTCMonth();
var day_out = e.getDate();
var year_out = e.getUTCFullYear();
date_out = month_out + "-" + day_out + "-" + year_out;
year = 2013
month = 12
day = 01
offset = 15
The offset is the “payment terms” and the date is the invoice date. The output is supposed to be the invoice date plus the offset to arrive at “12-16-2013”
That is NOT what it is kicking out and I need to figure out how to fix it.
One customer is having dates show up as: 0-16-2014
I don’t know which string is wrong or how it should read in its place. This is one piece of an entire function that pulls an invoice date from an XML file, strips the time from the date and creates a new "Date_Due" using the offset. This script is the only area that is failing.
Can anyone help?
getUTCMonth() returns 0 based months - 0 is January, 1 is February, etc.
Add 1 to this value to make it more human readable.
See docs for more info.
I am having some difficulties getting a field to populate in an interactive PDF form. I am using a javascript to calculate the current age of client from 2 date fields (DateToday and ClientDOB) already in the form and I need it to populate a "ClientAge" field. The DateToday field automatically populates when the form is opened. I would like for the ClientAge field to populate after the user selects the ClientDOB.
This is what I am trying to have it do. Should be simple I would think.
DateToday - ClientDOB = ClientAge
Here is my code:
var DateToday_ = Date2Num(DateToday.formattedValue, "MM/DD/YYYY")
var ClientDOB_ = Date2Num(ClientDOB.formattedValue, "MM/DD/YYYY")
var diff = DateToday_ - ClientDOB_
ClientAge.value = Floor(diff / 365.25)
I am not sure why the ClientAge field will not populate once the ClientDOB has been selected. Any replies would be helpful. Thanks.
This was taken from somewhere off the 'net. Can' remember where. However I have used this in a number of forms and it works fine. The idea is that the difference between dates is in milliseconds, and a given date is the number of seconds from a fixed date in the past. Once you have the difference in seconds between the dates (in this case DOB to the present) you can calculate how many years that is. Note that my format is in British date format (dd/mm/yy). If you operate in American format (mm/dd/yy) you must make the appropriate changes.
// get current date THIS NON AMERCAN DATE FORMAT
var oNow = new Date();
// get date from 'Demo.DOB' field
var oMyDate = util.scand('dd/mm/yy', this.getField('Demo.DOB').value);
// define second in milliseconds
var nSec = 1000;
// define minute in milliseconds
var nMin = 60 * nSec;
// define hour in milliseconds
var nHr = 60 * nMin;
// define day in milliseconds
var nDay = 24 * nHr;
// compute today as number of days from epoch date
var nNowDays = Number(oNow) / nDay;
// truncate to whole days
nNowDays = Math.floor(nNowDays);
// compute inputted date days from epoch data
var nMyDateDays = Number(oMyDate) / nDay;
// truncate to whole days
nMyDateDays = Math.floor(nMyDateDays);
// compute difference in the number of days
var nDiffDays = nNowDays - nMyDateDays;
// adjust difference for counting starting day as 1
++nDiffDays;
// convert days to years
var nYears = nDiffDays / 365.2525
// truncate to whole years
nYears = Math.floor(nYears);
// set field value number of years (nYears)
event.value = nYears;
I'm looking for a HTML code that adds a fixed number of days to an entered Date of Birth. Thanks a lot! Even a partial code is much appreciated!
Here is how I'd do it. The function daysFromDate returns a Date object you can use. Instead of passing the DOB as a string you can also update it to use a Date object.
/*
days is the number of days to add, and dob a string like "4/24/2011"
*/
function daysFromDate(days, dob) {
var dates = dob.split('/');
var daysToMilli = days * 60 * 60 * 24 * 1000;
var d = new Date(parseInt(dates[2]), parseInt(dates[0])-1, parseInt(dates[1]));
var newTime = d.getTime() + daysToMilli;
return new Date(newTime);
}
To get the date 20 days from now you call: daysFromDate(20, "4/24/2011");
VBScript has DateAdd() so it's pretty simple. If you prefer JavaScript, just Google "javascript dateAdd" -- there are a zillion solutions out there. Here's one:
http://www.solutionbot.com/2008/06/20/javascript-dateadd-function/