Please help me get the number of days between today's date and some other date.. Here is my example
It gives me NaN
Here is what I came up with. My demo
var cellvalue="2011-08-18 11:49:01.0 IST";
var firstDate = new Date();
var secondDate = cellvalue.substring(0, cellvalue.length-4);
alert(diffOf2Dates(firstDate,secondDate));
function diffOf2Dates(todaysDate,configDate)
{
/*var udate="2011-08-18 11:49:01.0";
var configDate=new Date(udate);*/
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = todaysDate; // Todays date
var secondDate = new Date(configDate);
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));
console.info(firstDate+", "+secondDate);
//console.info(Math.ceil(diffDays));
return Math.ceil(diffDays);
}
Use
var firstDate = new Date(); // Todays date
var secondDate = new Date(2011,08,19, 11,49,01);
var diffDays = (firstDate.getDate() - secondDate.getDate());
It was showing NAN as your constructor is wrong. check yourself by alerting secondDate in your original code
Edit : above code will work if both dates are in same month, for general case
var oneDay = 24*60*60*1000;
var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime()) / oneDay);
Also this will give result as fraction of date, so if you want to count whole dates you can use Math.ceil or Math.floor
Use this:
var udate="2011-08-19 11:49:01.0 GMT+0530";
The IST part is not valid
your input date is incorrect that is why it is failing. anyways here is some code that should help you with it.
var DateDiff = {
inDays: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000));
},
inWeeks: function(d1, d2) {
var t2 = d2.getTime();
var t1 = d1.getTime();
return parseInt((t2-t1)/(24*3600*1000*7));
},
inMonths: function(d1, d2) {
var d1Y = d1.getFullYear();
var d2Y = d2.getFullYear();
var d1M = d1.getMonth();
var d2M = d2.getMonth();
return (d2M+12*d2Y)-(d1M+12*d1Y);
},
inYears: function(d1, d2) {
return d2.getFullYear()-d1.getFullYear();
}
}
var udate="2011-08-05 11:49:01";
var configDate=new Date(udate);
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(); // Todays date
var secondDate = new Date(udate);
alert(secondDate);
var diffDays = DateDiff .inDays(firstDate,secondDate);
alert(diffDays );
if you have udate format like 28-07-2011 you can use this
var checkindatestr = "28-07-2011";
var dateParts = checkindatestr.split("-");
var checkindate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0]);
var now = new Date();
var difference = now - checkindate;
var days = difference / (1000*60*60*24);
alert(days);
how to compare two dates in jquery
You are calculating the difference correctly but the problem is that secondDate is an invalid date. Date cannot work with that date format, it needs "August 08, 2011 11:49:01" as input - and if your date has a different format then you have to convert it. Note that Date has only rudimentary timezone recognition, you can only be sure that "UTC" or "GMT" will be recognized correctly - you shouldn't use other time zones.
The problem is with your udate variable value. The date format is not correct. Try initializing the date in this format:
var secondDate = new Date(year,month,date);
Related
I converted my start and end date to .ToLocalString and now I am trying to use math.abs to calculate difference between start and end date in numbers but its Value is NaN. Any suggestions on how to apply Math.abs in this situation are appreciated.
Note: Start date will be in EDT and EndDate will be in EST. But they
might or might not be in same timezone.
var startDate1 = new Date(homeCtrl.createStartDate);
var startDate = startDate1.toLocaleString();
var endDate1 = new Date(homeCtrl.createEndDate);
var endDate = endDate1.toLocaleString();
var timeDiff = Math.abs(endDate - startDate); //This is NaN
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); // Here it will add 1 extra day. Example: 11/06/2018 - 11/04/2018 = 2 days but this gives 3days are timezone change on 11/04/2018 and thats the issue.
I would use the unix timestamp.
var startDate1 = new Date(homeCtrl.createStartDate);
var startDate = startDate1.getTime();
var endDate1 = new Date(homeCtrl.createEndDate);
var endDate = endDate1.getTime();
var timeDiff = Math.abs(endDate - startDate);
I have following code. I'm trying to calculate date difference but it's output is NaN. Any idea where I am wrong ?
var start = "01/01/2018"; //dd/mm/yyyy format
var end = "09/01/2018"
var date1 = new Date(start);
var date2 = new Date(end);
var timeDiff = Math.abs(date1.getTime() - date2.getTime());
var diffDays = Math.ceil(parseInt((date2 - date1) / (24 * 3600 * 1000)));
alert(diffDays);
It has been solved by below code. Hope It will help others too.Thanks for everyone
var start = "01/01/2018";
var startD = new Date(start);
var end = "09/01/2018";
var endD = new Date(end);
var report_date_string = new String(start);
var rectify_date_string = new String(end);
var report_date_final = report_date_string.split('/');
var month1 = report_date_final[0];
var day1 = report_date_final[1];
var year1 = report_date_final[2];
var rectify_date_final = rectify_date_string.split('/');
var month2 = rectify_date_final[0];
var day2 = rectify_date_final[1];
var year2 = rectify_date_final[2];
var report_datetime = new Date(year1, day1,month1 - 1);
var rectify_datetime = new Date(year2, day2,month2 - 1);
var diff = Math.abs(((rectify_datetime.getTime() - report_datetime.getTime()) / (24 * 3600 * 1000)));
alert(diff);
I have no idea why you were getting NaN - I suspect you're running subtly different code to what you showed here, but you should be aware that the browswer is interpreting 09/01/2018 as the 1st September, not the 9th January as you expect - and as a result of using Math.abs you're actually getting a value of 242, where I suspect you're expecting 8.
The solution is to use a non-ambiguous format for specifying dates, which is yyyy-mm-dd. This is evaluated correctly in all cases.
The following code works (and gives the expected answer) on Chrome, FF & IE/Edge
var start = "2018-01-01"; // yyyy-mm-dd format
var end = "2018-01-09"
var date1 = new Date(start);
var date2 = new Date(end);
var timeDiff = Math.abs(date1.getTime() - date2.getTime());
var diffDays = Math.ceil(parseInt((date2 - date1) / (24 * 3600 * 1000)));
console.log(diffDays);
I have to compare two date times in javascript. The dates I have are of the form
YYYY-MM-DD HH:MM:SS.
I am using the below code for it
var date1 = new Date("2015-08-20 09:38:20");
var date2 = new Date("2015-08-20 08:00:00");
The problem here is that when I use "/" in place of "-", I get the expected results. But when for this format I do
date1 > date
It returns false
Using momentJs is not an option for me and also I am getting the dates from soemewhere so would have to preserve the format. How do I compare the dates of the above given format in javascript
Try this:
var date1 = '2015-08-20 09:38:20';
var date2 = '2015-08-20 08:00:00';
var date1Updated = new Date(date1.replace(/-/g,'/'));
var date2Updated = new Date(date2.replace(/-/g,'/'));
console.log(date1Updated > date2Updated);
I was not able to reproduce the given behavior, but you could try
converting the date1 and date2 variables to miliseconds and storing those in separate vars since Jan 1st 1970.
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
this gives ( for your given example )
1440056300000
1440050400000
and in a comparison
date1_ms > date2_ms
returns true
This is typical of JavaScript dates. All browsers seem to treat date strings differently. My experience is write your own parser if you know the format you want to deal with.
Something like the below will work. Feel free to tidy it up and make it more generic for your own use.
function parseDateString(dateString) {
var dateParts = dateString.split(' ');
var dateOnlyString = dateParts[0];
var timeString = dateParts[1];
var dateOnlyParts = dateOnlyString.split('-');
var year = dateOnlyParts[0];
var month = dateOnlyParts[1] - 1;
var day = dateOnlyParts[2];
var timeParts = timeString.split(':');
var hours = timeParts[0];
var minutes = timeParts[1];
var seconds = timeParts[2];
return new Date(year, month, day, hours, minutes, seconds);
}
jsfiddle for test: http://jsfiddle.net/04nh4q9w/
function getDate(dateString) {
//This function assumes that the dateString will always be of the format YYYY-MM-DD HH:MM:SS
var dateParts = dateString.split(' ');
var dateStr = dateParts[0].split('-');
var timeStr = dateParts[1].split(':');
var dateTimeArr = datestr.concat(timestr)
return new Date(dateTimeArr[0], dateTimeArr[1]-1, dateTimeArr[2], dateTimeArr[3], dateTimeArr[4], dateTimeArr[5]);
}
var date1 = getDate("2015-08-20 09:38:20");
var date2 = getDate("2015-08-20 08:00:00");
date1 > date2 will be true for any browser.
function convertTo24Hour(time) {
time = time.toUpperCase();
var hours = parseInt(time.substr(0, 2));
if(time.indexOf('AM') != -1 && hours == 12) {
time = time.replace('12', '0');
}
if(time.indexOf('PM') != -1 && hours < 12) {
time = time.replace(hours, (hours + 12));
}
return time.replace(/(AM|PM)/, '');
}
I am using momentjs for date and I have one date string, ie,"2015-05-10",I want to get date difference from today
var today= moment().format('YYYY-MM-DD');
How it is possible here?
here is a example,
var now = moment(); // moment object of now
var day = moment("2015-05-13"); // moment object of other date
$scope.difference = now.diff(day, 'days'); // calculate the difference in days
$scope.difference = now.diff(day, 'hours'); // calculate the difference in hours
check more options here
here is a example
You can use diff
//Convert to date
var today = moment();
var date = moment("2015-05-13", "YYYY-MM-DD");
//Use diff
var duration = today.diff(date);
var hours = duration.asHours();
if you are talking about time difference in hours
var now = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";
var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
While working with date difference, when I am using below code somehow function is assuming that all the months have 31 days. For ex. if I am subtracting 01-March with 28-February the difference is coming as 4 days. Is there any simple way to twick this. Any help will be appreciated.
function myFunction()
{
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2);
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2);
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var x = document.getElementById("demo");
x.innerHTML=(n1-n)/(1000*24*60*60);
}
This will give you the difference between two dates, in milliseconds
var diff = Math.abs(date1 - date2);
example, it'd be
var diff = Math.abs(new Date() - compareDate);
You need to make sure that compareDate is a valid Date object.
Something like this will probably work for you
var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/')));
i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.
U can subtract like this--
var d1 = new Date(); //"now"
var d2 = new Date("2011/02/01") // some date
var diff = Math.abs(d1-d2); // difference in milliseconds
var days = diff*24*60*60*1000;
You code is actually subtracting March 1 from April 1, as the months in JavaScript dates are 0-based.
var sysdt = "02/28/2013";
var date1 = new Date(sysdt);
var userdt = "03/01/2013"
var date2 = new Date(userdt);
var days = (date2-date1)/(1000*24*60*60);
or subtract 1 from month in your code
var sysdt = "02/28/2013";
var year = sysdt.substring(6,10);
var mon = sysdt.substring(0,2)-1; // months are from 0 to 11
var date = sysdt.substring(3,5);
var n = Date.UTC(year,mon,date);
var userdt = "03/01/2013"
var yr = userdt.substring(6,10);
var mn = userdt.substring(0,2)-1; // months are from 0 to 11
var dd = userdt.substring(3,5);
var n1 = Date.UTC(yr,mn,dd);
var days = (n1-n)/(1000*24*60*60);