Javascript / jQuery two datepickers calculate date range - javascript

I use the Javascript below to calculate days out of a date range (2 Zebra Datepickers) and to pass the value to input field 'nights' .. then process a form.
While my Javascript works fine, i fail to achieve the same result with jQuery .val()
Javascript:
setDifference = function(form)
{
var x = document.getElementById('startDate').value;
var y = document.getElementById('endDate').value;
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('nights').value = (dt2.valueOf() - dt1.valueOf()) / (60 * 60 * 24 * 1000)
}
jQuery i tried so far:
$(function() {
var startDate = $('#startDate').val();
var endDate = $('#endDate').val();
var dateSplit = startDate.split("-");
var dateSplit = endDate.split("-");
dateDiff = new Date(dateSplit[1] + " " + dateSplit[0] + ", " + dateSplit[2]);
var dateDiff = new Date(endDate - startDate);
var days = dateDiff/1000/60/60/24;
$('#nights').val(days);
});
Error i get is either 'NaN or 'invalid date' on all browsers i tried.

You have declared dateSplit two times. hence startdate and enddate would be same.

Related

Calculate age in JS given the birth date in "dd/mm/yyyy" format

I am trying to write a function in JavaScript to calculate age.
I wrote a function but it does not give accurate age.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], [1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
I try calculateAge("25/11/1993") and I don't get accurate age. Kindly guide me.
You missed the formattedDate for [1] in the new Date() function, so formattedDate[1] it should be.
function calculateAge(date) {
var formattedDate = date.split("/")
var birthdateTimeStamp = new Date(formattedDate[2], formattedDate[1], formattedDate[0])
var currentDate = new Date().getTime();
var difference = currentDate - birthdateTimeStamp;
var currentAge = Math.floor(difference / 31557600000)
// dividing by 1000*60*60*24*365.25
return currentAge
}
var age = calculateAge('25/11/1993');
console.log('My age is', age);

Getting NaN when calculating difference of two dates using Javascript

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

How to calculate time from now in javascript?

I'm a code newbie so forgive me if the answer to this question is obvious!
I'm collecting JSON data from an API and I have a value, ExpectedDateTime, which I'd like to use to calculate the number of minutes and seconds from now.
It has the format: 2016-05-09T12:26:26
I've tried this:
function applyTimeToVallingby(data) {
$scope.timeToVallingby = 0;
$scope.timeToVallingby2 = 0;
d = new Date();
for(i=0;i<data.ResponseData.Buses.length;i++){
if(data.ResponseData.Buses[i].JourneyDirection === 2){
if($scope.timeToVallingby===0){
$scope.timeToVallingby=(d-data.ResponseData.Buses[i].ExpectedDateTime);
}else if($scope.timeToVallingby!=0&&$scope.timeToVallingby2===0){
$scope.timeToVallingby2=d-data.ResponseData.Buses[i].ExpectedDateTime;
}
}
}
}
But it doesn't work. I've tried to find a way to convert the new Date() value to something similar to the format of ExpectedDateTime, so that I can just subtract, but haven't been able to.
Best regards,
Kind of diff of time :
var date = new Date('2016-05-09T12:26:26');
var now = new Date();
alert(" Seconds from now : " + parseInt( (now.getTime() - date.getTime())/1000 ) );
In your way - d.getTime() - new Date( data.ResponseData.Buses[i].ExpectedDateTime).getTime()
You need to first convert ExpectedDateTime to a Date Object
var expectedDateTime = "2016-05-09T12:26:26";
var items = expectedDateTime.split("T");
var dates = items[0].split("-");
var times = items[1].split(":");
var expectedDateObj = new Date( dates[0], dates[1]-1, dates[2], times[0], times[1], times[2] );
Now simple get the number of Milliseconds difference from now and this expectedDateObj object
var now = new Date();
var noOfMS = now.getTime() - expectedDateObj.getTime();
var numberOfSeconds = noOfMS/1000;
var noOfMinAndSec = "Min = " + numberOfSeconds/60 + " Sec = " + numberOfSeconds%60;
DEMO
var expectedDateTime = "2016-05-09T12:26:26";
var items = expectedDateTime.split("T");
var dates = items[0].split("-");
var times = items[1].split(":");
var expectedDateObj = new Date( dates[0], dates[1]-1, dates[2], times[0], times[1], times[2] );
var now = new Date();
var noOfMS = now.getTime() - expectedDateObj.getTime();
var numberOfSeconds = Math.floor(Math.abs(noOfMS/1000));
var noOfMinAndSec = "Min = " + parseInt(numberOfSeconds/60) + " Sec = " + numberOfSeconds%60;
alert( noOfMinAndSec );
Maybe you could use Moment.js library:
$scope.daysLeft = function (end_date) {
var now = moment();
var then = moment(end_date);
var diff = then.diff(now, 'days');
if(diff <= 0)
return 0;
return diff;
}

Adding a week to date javascript

I have a JSfiddle which I am trying to add a week onto a date. The date is outputting incorrect date when I try to add six days.
fiddle
code for adding a week
var endDate = new Date(date || Date.now()),
eMonth = '' + (monthNames[endDate.getMonth()]),
eDay = '' + (endDate.setDate(endDate.getDate() + 6)),
eYear = endDate.getFullYear();
Try this,
var endDate = new Date(date || Date.now());
var days = 6;
endDate.setDate(endDate.getDate() + days);
var eMonth = '' + (monthNames[endDate.getMonth()]),
eDay = '' + endDate.getDate(),
eYear = endDate.getFullYear();
Working Demo
Give this a try,
var endDate = new Date(date || Date.now());
endDate.setTime(startDateObj.getTime() + (1000 * 60 * 60 * 24 * 7));
var newDate = endDate.getFullYear()+"-"+(endDate.getMonth() + 1)+"-"+endDate.getDate();
eDay = '' + (endDate.getDate() + 6)
Remove setDate() function and change $("#startDate").text(startDate) to show value in span tag
var now = new Date().getTime();
var oneWeek = 6*24*60*60*1000;
var newDate = now+oneWeek;
alert(new Date(newDate));
this should do the work
You can also use the get/set Time methods:
var today = new Date();
var plusOneWeek = new Date();
plusOneWeek.setTime( today.getTime()+(7*24*3600*1000) ); //add 7 days
See the doc about getTime() on MDN

Count Number of days between 2 dates in javascript

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

Categories

Resources