How can I count the days between two dates in javascript? [duplicate] - javascript

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.

Related

Comparing two Dates and returning in correct format

I have a requirement where I need to compare two date values (Past Date and the Present Date) and return the exact difference in year/month/day and if it exceeds 59 years 6 month even a single day then it should return over age else under age
I searched in web but not getting anything relevant to it.
Currently I am trying:
var start_date = new Date("1990-04-25");
var end_date = new Date();
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
if (total_months < 714) {
alert("under age")
} else { alert("over age") }
where I am converting the years to month, which is not giving me the exact result.
Can some one please help me to solve this.
var start_date = new Date("1990-04-25");
var end_date = new Date();
var millisec = Math.abs(end_date - start_date); // it will provide you miliseconds
// here you can convert it to days or month and check for over or under age
e.g
var seconds = (millisec / 1000).toFixed(1);
var minutes = (millisec / (1000 * 60)).toFixed(1);
var hours = (millisec / (1000 * 60 * 60)).toFixed(1);
var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);
for More help refer to these :
1. How to subtract date/time in javascript?
2. Convert time interval given in seconds into more human readable form

set javascript date object to before 30 days

Lets say now the date is 10/07/2015, ie If I create a javascript date object like as shown below I will get todays date as 07/10/2015
var now = new Date();
So if the date is 10/07/2015 I want 30 days back date i.e 07/09/2015.
I did like as shown below but for that I got 31/08/2015
var now = new Date();
now .setDate(-30);
Can anyone please tell me some solution for this
You can try like this:
Date.today().add(-30).days();
And if you want then moment.js is really good when dealing with dates
moment().subtract(30, 'days');
And if you dont want to use any library then
var now = new Date()
var prev = new Date().setDate(now.getDate()-30)
You could have simply use now.getDate():
var now = new Date();
document.write(now);
now.setDate(now.getDate() - 30);
document.write("<br/>");
document.write(now);
A Date object internally contains a value that corresponds to the number of milliseconds passed since 1 January, 1970 UTC.
As such, using this value (accessible via Date.prototype.valueOf()) you can add or subtract any size of "simply calculated" time interval. By simply calculated I mean anything that can be calculated using simple arithmetics, such as (for example..) "1 day 4 hours and 2 minutes" is equal to (((1 * 24) + 4) * 60 + 2) * 60 * 1000. You can add / subtract that to any starting time and create a new Date object:
var startDate = new Date();
var newDate = new Date(startDate.valueOf() + ((((1 * 24) + 4) * 60 + 2) * 60 * 1000));
alert(newDate);
In the specific case of days offset, simply use this formula:
days * 24 * 60 * 60 * 1000

Number of weeks between two dates using JavaScript

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

difference between 2 dates

I have to simply calculate difference between two dates, and display it as integer but my code below gives errors if there are large amount of dates (more than 26) in between 2 dates, as well as if there is a date "31st" of a month in between 2 dates.
Can not find whats wrong with my code...?
The values of 'ires_sakuma_datums' and 'ires_beigu_datums' are set by jquery calendar picker and are displayed in the format e.g. 25-08-2012 and 17-09-2012 respectively and the result should be displayed into id 'dienu_skaits'
Example 'ires_sakuma_datums' is set to 28-08-2012 and 'ires_beigu_datums' is set to 29-09-2012 and it results into 31.041666666666668 although I would expect to result into 32
function getDays()
{
var x = document.getElementById('ires_sakuma_datums').value;
var y = document.getElementById('ires_beigu_datums').value;
//assuming that the delimiter for dt time picker is a '-'.
var arr1 = x.split('-');
var arr2 = y.split('-');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
document.getElementById('dienu_skaits').value = (dt2.valueOf() - dt1.valueOf()) / (60 * 60 * 24 * 1000);
document.forms['test'].elements['dienu_skaits'].focus();
}
The problem is that months to be passed to Date are 0 based , so you have to subtract 1 from the month. http://jsfiddle.net/qB9V3/5/ Therefore, your comparison between 28-08-2012 and 29-09-2012 was actually diffing 28-09-2012 and 29-10-2012
So your code would need to change to be
var arr1 = x.split('-');
var arr2 = y.split('-');
var dt1 = new Date();
dt1.setFullYear(arr1[2], parseInt(arr1[1],10) -1, arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], parseInt(arr2[1],10) - 1, arr2[0]);
Beware that if your dates cross daylight savings changes, the number of days in between won't be even, so you'll need to round the result
document.getElementById('dienu_skaits').value = Math.round(
(dt2 - dt1) / (60 * 60 * 24 * 1000)
);

JQuery DateTime - compare days

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)
}

Categories