just wodnering if it's possible to compare the difference in days between two dates, I have done this in c# like so, but can it be done in JQuery?
TimeSpan span = DateTime.Now - LastDate;
if (span.Days > 3)
{
}
else
{
}
Anyone have any ideas?
Cheers
Here's a javascript function to get the days between 2 dates in javascript, no need for jquery here;
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
Related
Trying to change this function from Get difference between 2 dates in javascript? to return difference in hours instead of days, but no luck so far. =)
function dateDiffInDays(scheduled, due) {
var _MS_PER_DAY = 1000 * 60 * 60 * 24;
var scheduled = new Date(scheduled);
var due = new Date(due);
var utc1 = Date.UTC(scheduled.getFullYear(), scheduled.getMonth(), scheduled.getDate());
var utc2 = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
Changed _MS_PER_DAY to 1000 * 60 * 60, but it wont work returning zeros. Please help.
EDIT: values of schedule and due in this format: "09/21/2014 09:00:00 am"
In your question, these lines:
var utc1 = Date.UTC(scheduled.getFullYear(), scheduled.getMonth(), scheduled.getDate());
var utc2 = Date.UTC(due.getFullYear(), due.getMonth(), due.getDate());
Scrub the hour/minute/etc. information from the dates, so if the two dates fall on the same day, the result will always be zero.
A much simpler function can be used to get the difference in hours (as a decimal number):
function dateDiffInHours(date1, date2) {
var msDiff = date2.getTime() - date1.getTime();
return msDiff / 3600000;
}
Or if you want it as a rounded/floored int, then apply Math.round() or Math.floor() to the returned result.
Converting to UTC at all is unnecessary.
I'm trying to return the number of weeks between two dates using JavaScript.
So I have the following variables:
var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if(day < 10) { day= '0' + day; }
if(month < 10) { month = '0' + month; }
var dateToday = day + '/' + month + '/' + year;
var dateEndPlacement = '22/06/2014';
I've also prefixed the days and months with 0 if they are less than 10. Not sure if this is the correct way to do this... so alternative ideas would be welcomed.
And then I pass these two dates to the following function:
function calculateWeeksBetween(date1, date2) {
// The number of milliseconds in one week
var ONE_WEEK = 1000 * 60 * 60 * 24 * 7;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to weeks and return hole weeks
return Math.floor(difference_ms / ONE_WEEK);
}
However I get the error:
Uncaught TypeError: Object 04/04/2014 has no method 'getTime'
Any ideas what I am doing wrong?
For those that are asking/gonna ask, I'm calling the function like this:
calculateWeeksBetween(dateToday, dateEndPlacement);
I would recommend using moment.js for this kind of thing.
But if you want to do it in pure javascript here is how I would do it:
function weeksBetween(d1, d2) {
return Math.round((d2 - d1) / (7 * 24 * 60 * 60 * 1000));
}
Then call with
weeksBetween(new Date(), new Date(2014, 6, 22));
You are storing your dates as strings ('22/06/2014'). getTime is a method of Date. You need to create Date objects for the dates, and pass those into the function.
var dateToday = new Date(year, month - 1, day);
var dateEndPlacement = new Date(2014, 5, 22);
calculateWeeksBetween(dateToday, dateEndPlacement);
As #Mosho notes, you can also subtract the dates directly, without using getTime.
If you need actual weeks between to dates, and not the number of seven days between them:
const week = 7 * 24 * 60 * 60 * 1000;
const day = 24 * 60 * 60 * 1000;
function startOfWeek(dt) {
const weekday = dt.getDay();
return new Date(dt.getTime() - Math.abs(0 - weekday) * day);
}
function weeksBetween(d1, d2) {
return Math.ceil((startOfWeek(d2) - startOfWeek(d1)) / week);
}
You can use moment itself have all the functionality I mentioned the below code which could work perfectly
var a = moment(a, 'DD-MM-YYYY');
var b = moment(b, 'DD-MM-YYYY');
days=b.diff(a, 'week');
don't forget to use moment js CDN
subtract dates (which, unformatted, are the number of seconds elapsed since 1 January 1970 00:00:00) , divide by 604,800,000 (milliseconds per week).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
You should convert dateToday and dateEndPlacement to Date type.
Please read Converting string to date in js
I am trying to compare two dates in javascript, which are in two input type="text", and that have the format "06/11/2013 13:24".
Any idea of how to compare them?
Thanks!
You need to parse string to Date - object:
var firstDate = new Date("06/11/2013 13:24");
var secondDate = new Date(youSecondDateString);
Age from Date of Birth using JQuery
Possibly a duplicate question to above but the answers is
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
//perform desired operation here
}
The Date object will do what you want - construct one for each date, then just compare them using the usual operators.
For example, subtracting date1 from date2 will give you the number of milliseconds between two dates.
You can get the number of seconds by dividing the milliseconds by 1000, and rounding the number:
var seconds = Math.round((date2-date1)/1000);
You could then divide by 60 to get the minutes, again by 60 to get the hours, then by 24 to get the days (and so on).
Here's how you might get a figure in the format dd:hh:mm
window.minutesPerDay = 60 * 24;
function pad(number) {
var result = "" + number;
if (result.length < 2) {
result = "0" + result;
}
return result;
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var days = totalMinutes / minutesPerDay;
totalMinutes -= minutesPerDay * days;
var hours = totalMinutes / 60;
totalMinutes -= hours * 60;
return days + ":" + pad(hours) + ":" + pad(totalMinutes);
}
var date1 = new Date("06/11/2013 13:24"),
date2 = new Date("07/11/2013 13:24"),
milliseconds = date2 - date1;
alert(millisToDaysHoursMinutes(milliseconds));
Fiddle
I took the millisToDaysHoursMinutes function from here.
I have two input dates taking from Date Picker control. I have selected start date 2/2/2012 and end date 2/7/2012. I have written following code for that.
I should get result as 6 but I am getting 5.
function SetDays(invoker) {
var start = $find('<%=StartWebDatePicker.ClientID%>').get_value();
var end = $find('<%=EndWebDatePicker.ClientID%>').get_value();
var oneDay=1000 * 60 * 60 * 24;
var difference_ms = Math.abs(end.getTime() - start.getTime())
var diffValue = Math.round(difference_ms / oneDay);
}
Can anyone tell me how I can get exact difference?
http://momentjs.com/ or https://date-fns.org/
From Moment docs:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // =1
or to include the start:
a.diff(b, 'days')+1 // =2
Beats messing with timestamps and time zones manually.
Depending on your specific use case, you can either
Use a/b.startOf('day') and/or a/b.endOf('day') to force the diff to be inclusive or exclusive at the "ends" (as suggested by #kotpal in the comments).
Set third argument true to get a floating point diff which you can then Math.floor, Math.ceil or Math.round as needed.
Option 2 can also be accomplished by getting 'seconds' instead of 'days' and then dividing by 24*60*60.
If you are using moment.js you can do it easily.
var start = moment("2018-03-10", "YYYY-MM-DD");
var end = moment("2018-03-15", "YYYY-MM-DD");
//Difference in number of days
moment.duration(start.diff(end)).asDays();
//Difference in number of weeks
moment.duration(start.diff(end)).asWeeks();
If you want to find difference between a given date and current date in number of days (ignoring time), make sure to remove time from moment object of current date as below
moment().startOf('day')
To find difference between a given date and current date in number of days
var given = moment("2018-03-10", "YYYY-MM-DD");
var current = moment().startOf('day');
//Difference in number of days
moment.duration(given.diff(current)).asDays();
Try this Using moment.js (Its quite easy to compute date operations in javascript)
firstDate.diff(secondDate, 'days', false);// true|false for fraction value
Result will give you number of days in integer.
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
This works for me:
const from = '2019-01-01';
const to = '2019-01-08';
Math.abs(
moment(from, 'YYYY-MM-DD')
.startOf('day')
.diff(moment(to, 'YYYY-MM-DD').startOf('day'), 'days')
) + 1
);
I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {
const getDateAsArray = (date) => {
return moment(date.split(/\D+/), date_format);
}
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;
}
console.log(getDaysDiff('2019-10-01', '2019-10-30'));
console.log(getDaysDiff('2019/10/01', '2019/10/30'));
console.log(getDaysDiff('2019.10-01', '2019.10 30'));
console.log(getDaysDiff('2019 10 01', '2019 10 30'));
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));
console.log(getDaysDiff('10-01-2019', '10-30-2019'));
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
Also you can use this code: moment("yourDateHere", "YYYY-MM-DD").fromNow(). This will calculate the difference between today and your provided date.
// today
const date = new Date();
// tomorrow
const nextDay = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
// Difference in time
const Difference_In_Time = nextDay.getTime() - date.getTime();
// Difference in Days
const Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to calculate the number of days between two dates using javascript
I have those dates :
27/09/2011
29/10/2011
and I'd like to return the days between those dates (in the example, should be 33 days).
How can I do it on javascript (or jquery?)?
var daysBetween = (Date.parse(DATE1) - Date.parse(DATE2)) / (24 * 3600 * 1000);
function days_between(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)
}
http://www.mcfedries.com/JavaScript/DaysBetween.asp
// split the date into days, months, years array
var x = "27/09/2011".split('/')
var y = "29/10/2011".split('/')
// create date objects using year, month, day
var a = new Date(x[2],x[1],x[0])
var b = new Date(y[2],y[1],y[0])
// calculate difference between dayes
var c = ( b - a )
// convert from milliseconds to days
// multiply milliseconds * seconds * minutes * hours
var d = c / (1000 * 60 * 60 * 24)
// show what you got
alert( d )
Note:
I find this method safer than Date.parse() as you explicitly specify the date format being input (by splitting into year, month, day in the beginning). This is important to avoid ambiguity when 03/04/2008 could be 3rd of April, 2008 or 4th of March, 2008 depending what country your dates are coming from.