subtract dates using jquery date picker - javascript

Currently working on jquery clone and datepicker where it will calulate the dates and it will check the overlaping dates. But if the click the less button the code works perfectly it was removing the row but it was not detecting the dates which was there in the cloned div. For example when the user select the date 10-01-1990 & 10-01-1995 for this the total was Total work experience 5 years 0 Months & in the cloned div if the user gave 10-01-1996 & 10-01-2015 so the total was Total work experience 25 years 0 Months. If the user click the lessbtn button the cloned one will remove but the total year was not detecting.
Here is the jquery code
$(document).on('change', ".datepicker", function (){
var valid=true;
$.each($('.datepicker'),function(){
if($(this).val()=="")
{
valid=false;
return false;
}
});
if(valid)
{
var dateStart=[];
var dateEnd=[];
$.each($('.datepicker'),function(){
if($(this).hasClass('startDate'))
dateStart.push($(this).val())
else
dateEnd.push($(this).val())
});
$.each($(dateStart),function(key,value){
var x = dateStart[key].split("-");
var y = dateEnd[key].split("-");
var failed = false;
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var locDiffDays = parseInt((todate.getTime() - fromdate.getTime()) / (1000 * 60 * 60 * 24));
console.log(x);
console.log(y);
console.log(fromdate);
console.log(todate);
console.log(locDiffDays);
if(locDiffDays<0){
alert("To date " + dateEnd[key] + " should be greater then from date " + dateStart[key] );
console.log("invalid from and to dates"); failed = true; return false;
}
if(dateStart[key-1]){
var x1 = dateStart[key-1].split("-");
var y1 = dateEnd[key-1].split("-");
var fromdate1 = new Date(x1[2], x1[0] - 1, x1[1]);
var todate1 = new Date(y1[2], y1[0] - 1, y1[1]);
var locDiffDays1 = parseInt((todate1.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
console.log(x1);
console.log(y1);
console.log(fromdate1);
console.log(todate1);
console.log(locDiffDays1);
var locDiffDays2 = parseInt((fromdate.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays3 = parseInt((todate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays4 = parseInt((fromdate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
console.log("locDiffDays2: " + locDiffDays2);
if(locDiffDays2<0){
alert("From date " + dateStart[key] + " should be greater than previous from date " + dateStart[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
if(locDiffDays3<0){
alert("To date " + dateStart[key] + " should be greater than previous To date " + dateStart[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
if(locDiffDays4<0){
alert("From date " + dateStart[key] + " should be greater than previous To date " + dateEnd[key-1] );
console.log("invalid from dates"); failed = true; return false;
}
}
if(key == dateStart.length-1 && !failed){
var firstDate = dateStart[0].split('-');
firstDate = new Date(firstDate[2], firstDate[0] - 1, firstDate[1]);
var lastDate = dateEnd[dateEnd.length-1].split('-');
lastDate = new Date(lastDate[2], lastDate[0] - 1, lastDate[1]);
console.log(lastDate);
console.log(firstDate);
//var diffYears = (lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
var diffMonths = monthDiff(firstDate, lastDate);
//diffYears = parseInt(''+diffYears);
var diffYears = diffMonths/12;
diffYears = parseInt(''+diffYears);
diffMonths = diffMonths - (diffYears * 12)
document.getElementById("txt_expy").innerHTML = diffYears + " years";
document.getElementById("txt_expm").innerHTML = diffMonths + " Months";
}
});
Kindly please suggest me.
I am confused here do i want to put any count or something so when the user click the less button the count should reduce one and the value should get detected. Kindly give me tips here
Hereis the fiddle Link
Thanks & Regards

Your issue is you are not calling any logic to update the difference while removing the cloned object. You wrote code for updating the difference only in datepicker.change event.
Demo
Updated code:
$(document).on('change', ".datepicker", function() {
updateDiff()
});
$(document).on('click', ".btn_less1", function() {
var len = $('.cloned-row3').length;
if (len > 1) {
$(this).closest(".btn_less1").parent().parent().parent().remove();
updateDiff();
}
});
function updateDiff() {
var valid = true;
$.each($('.datepicker'), function() {
if ($(this).val() == "") {
valid = false;
return false;
}
});
if (valid) {
var dateStart = [];
var dateEnd = [];
$.each($('.datepicker'), function() {
if ($(this).hasClass('startDate')) dateStart.push($(this).val())
else dateEnd.push($(this).val())
});
$.each($(dateStart), function(key, value) {
var x = dateStart[key].split("-");
var y = dateEnd[key].split("-");
var failed = false;
var fromdate = new Date(x[2], x[0] - 1, x[1]);
var todate = new Date(y[2], y[0] - 1, y[1]);
var locDiffDays = parseInt((todate.getTime() - fromdate.getTime()) / (1000 * 60 * 60 * 24));
if (locDiffDays < 0) {
alert("To date " + dateEnd[key] + " should be greater then from date " + dateStart[key]);
console.log("invalid from and to dates");
failed = true;
return false;
}
if (dateStart[key - 1]) {
var x1 = dateStart[key - 1].split("-");
var y1 = dateEnd[key - 1].split("-");
var fromdate1 = new Date(x1[2], x1[0] - 1, x1[1]);
var todate1 = new Date(y1[2], y1[0] - 1, y1[1]);
var locDiffDays1 = parseInt((todate1.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays2 = parseInt((fromdate.getTime() - fromdate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays3 = parseInt((todate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
var locDiffDays4 = parseInt((fromdate.getTime() - todate1.getTime()) / (1000 * 60 * 60 * 24));
console.log("locDiffDays2: " + locDiffDays2);
if (locDiffDays2 < 0) {
alert("From date " + dateStart[key] + " should be greater than previous from date " + dateStart[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
if (locDiffDays3 < 0) {
alert("To date " + dateStart[key] + " should be greater than previous To date " + dateStart[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
if (locDiffDays4 < 0) {
alert("From date " + dateStart[key] + " should be greater than previous To date " + dateEnd[key - 1]);
console.log("invalid from dates");
failed = true;
return false;
}
}
if (key == dateStart.length - 1 && !failed) {
var firstDate = dateStart[0].split('-');
firstDate = new Date(firstDate[2], firstDate[0] - 1, firstDate[1]);
var lastDate = dateEnd[dateEnd.length - 1].split('-');
lastDate = new Date(lastDate[2], lastDate[0] - 1, lastDate[1]);
console.log(lastDate);
console.log(firstDate);
//var diffYears = (lastDate.getTime() - firstDate.getTime()) / (1000 * 60 * 60 * 24 * 365);
var diffMonths = monthDiff(firstDate, lastDate);
//diffYears = parseInt(''+diffYears);
var diffYears = diffMonths / 12;
diffYears = parseInt('' + diffYears);
diffMonths = diffMonths - (diffYears * 12)
document.getElementById("txt_expy").innerHTML = diffYears + " years";
document.getElementById("txt_expm").innerHTML = diffMonths + " Months";
}
});
}
}

Related

age calculator with javascript

I was trying to create an age calculator with javascript.There is a condition if the birthday input fileds are empty then it will give an error massage.but now even the filed are empty and click on the submite button it's submiting and giving an auot days month and year.How can I solve this issue.Here is my java script code
let presentdate = document.getElementById("pdate");
let presentmonth = document.getElementById("pmonth");
let presentyear = document.getElementById("pyear");
var date = new Date();
var pdate = date.getUTCDate(); //present date
var pmonth = 1 + date.getUTCMonth(); //present month
var pYear = date.getUTCFullYear(); // present year
var month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// present date , month and year
presentdate.value = pdate;
presentmonth.value = pmonth;
presentyear.value = pYear;
// set conditions
function isNum(arg) {
var args = arg;
if (args == "" || args == null || args.length == 0) {
return false;
}
// argument to set only number in input
args = args.toString();
for (var i = 0; i < args.length; i++) {
if (
(args.substring(i, i + 1) < "0" || args.substring(i, i + 1) > "9") &&
args.substring(i, i + 1) != "."
) {
return false;
}
}
return true;
}
// check date.it will set the date between 1-31.
function checkday(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 31) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
//check month.it will set month between 1-12.
function checkmonth(aa) {
var val = aa.value;
var valc = val.substring(0, 1);
if (val.length > 0 && val.length < 3) {
if (!isNum(val) || val == 0) {
aa.value = "";
} else if (val < 1 || val > 12) {
aa.value = valc;
}
} else if (val.length > 2) {
val = val.substring(0, 2);
aa.value = val;
}
}
function age() {
let bdate = +document.getElementById("date").value;
let bmonth = +document.getElementById("month").value - 1;
let byear = +document.getElementById("year").value;
if (bdate === "" || bmonth === "" || byear === "") {
document.getElementById("error").innerHTML = "Put Your Birthday";
return;
}else{
let current = new Date();
let birth = new Date(byear, bmonth, bdate);
let difference = current - birth;
let years = Math.floor(difference / (1000 * 60 * 60 * 24 * 365.25));
difference -= years * (1000 * 60 * 60 * 24 * 365.25);
let months = Math.floor(difference / (1000 * 60 * 60 * 24 * 30.4375));
difference -= months * (1000 * 60 * 60 * 24 * 30.4375);
let days = Math.floor(difference / (1000 * 60 * 60 * 24));
document.querySelector(".calc_result").style.display = "block";
document.getElementById(
"total_age"
).innerHTML = `${years} Years ${months} Months ${days} Days`;
calculateDaysLived();
calculateNextBirthday();
// remove error text
document.getElementById("error").innerHTML = "";
}
}
// total days
function calculateDaysLived() {
let today = new Date();
let birthdate = new Date(
document.getElementById("year").value,
document.getElementById("month").value - 1,
document.getElementById("date").value
);
let timeDifference = today - birthdate;
let daysLived = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
document.getElementById("total_day").innerHTML =
"You lived " + daysLived + " days Since Your Birthday";
}
// next birtday
function calculateNextBirthday() {
let today = new Date();
let birthdate = new Date(
document.getElementById("year").value,
document.getElementById("month").value - 1,
document.getElementById("date").value
);
birthdate.setFullYear(today.getFullYear());
while (birthdate < today) {
birthdate.setFullYear(birthdate.getFullYear() + 1);
}
document.getElementById("next_bday").innerHTML =
"Your next birthday is on " + birthdate.toDateString();
}
You're converting date inputs to numbers and you're comparing them to an empty string. It's going to always be false:
if (bdate === "" || bmonth === "" || byear === "") {
You can either check this condition before converting to numbers, or change the value you compare to.

how to check the diffrence between dates

I created a function to check the difference between a particular date and the current date, everything is working perfectly for past dates. But, when it comes to future dates, it gives the correct difference eg. the 18th of May is two days after the 16th of May, so the difference is 2, but I don't know if it's two days before or two days after. I cannot differentiate between future dates and past dates, whether the date is in the past or in the future.
here is my code:
function GetDateDiff(previousDate, previousTime) {
let today = new Date();
let dd = String(today.getDate()).padStart(2, "0");
let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = today.getFullYear();
let currentDate = mm + "/" + dd + "/" + yyyy; // this will give you the current date
let previousMinutes = previousTime.split(":")[1];
let previousSeconds = previousTime.split(":")[2];
let previousHours = previousTime.split(":")[0];
let timePeriod = "seconds"; // timePeriod is the current unit of mesearement whether in seconds hours or days
let timeInNumber = "0"; //timeInNumber is the number infront of the timeperiod eg the 40 in 40 minites is the timeInNumber
let dateObj = new Date();
// this is to set the appropriate seconds, minutes and hours
if (currentDate == previousDate) {
if (dateObj.getHours() == previousHours) {
if (dateObj.getMinutes() == previousMinutes) {
timeInNumber = dateObj.getSeconds() - previousSeconds;
timePeriod = "Second";
} else {
timeInNumber = dateObj.getMinutes() - previousMinutes;
timePeriod = "Minute";
}
} else {
timeInNumber = dateObj.getHours() - previousHours;
timePeriod = "Hour";
// timePeriod =dateObj.getHours();
}
} else {
const previousDateDifferential = new Date(previousDate);
const currentDateDifferential = new Date(currentDate);
const diffrenceInDate = Math.abs(
currentDateDifferential - previousDateDifferential
);
// this is to calculate the diffrence in days, weeks, months and years
const diffDays = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24));
const diffWeeks = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7));
const diffMonths = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4));
const diffyears = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4 * 12));
// this is to set the appropriate days, weeks, months and years
if (diffDays <= 30) {
timeInNumber = diffDays;
timePeriod = "Day";
} else if (diffDays > 30 && diffWeeks <= 4) {
timeInNumber = diffWeeks;
timePeriod = "Week";
} else if (diffWeeks > 4 && diffMonths <= 12) {
timeInNumber = diffMonths - 2;
timePeriod = "Month";
} else if (diffMonths > 12) {
timeInNumber = diffyears - 1;
timePeriod = "Year";
}
}
if (timeInNumber > 1) {
timePeriod += "s"// this is to ad 's' at the end of the time period if the time period is more than 1
}
return `${timeInNumber} ${timePeriod} Ago`;
}
if I write GetDateDiff("05/14/2022", "00:00:00") // result will be 2 days ago
if I write GetDateDiff("05/18/2022", "00:00:00") // result will still be 2 days ago, how can i make it 2 days later or check that the date is in the future
The best tip was given already: use > and < to compare dates. Here is an example to get you started:
// function GetDateDiff to get the difference to the current date including negative values
function GetDateDiff(date) {
// get current date
var currentDate = new Date();
// get the difference between the current date and the date passed in
var diff = date.getTime() - currentDate.getTime();
// Build string prefix for negative and positive dates
var diffString = diff < 0 ? "In the Past: " : "In the Future: ";
// get the absolute value of the difference
diff = Math.abs(diff);
// get the days, hours, minutes, and seconds from the difference
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((diff % (1000 * 60)) / 1000);
// return the difference in days, hours, minutes, and seconds
return diffString + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
}
// example usage
var date = new Date(2020, 0, 1, 0, 0, 0, 0);
var diff = GetDateDiff(date);
alert(diff);
var date = new Date(2024, 0, 1, 0, 0, 0, 0);
var diff = GetDateDiff(date);
alert(diff);
function GetDateDiff(previousDate, previousTime) {
let today = new Date();
let dd = String(today.getDate()).padStart(2, "0");
let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = today.getFullYear();
let currentDate = mm + "/" + dd + "/" + yyyy; // this will give you the current date
let previousMinutes = previousTime.split(":")[1];
let previousSeconds = previousTime.split(":")[2];
let previousHours = previousTime.split(":")[0];
let timePeriod = "seconds"; // timePeriod is the current unit of mesearement whether in seconds hours or days
let timeInNumber = "0"; //timeInNumber is the number infront of the timeperiod eg the 40 in 40 minites is the timeInNumber
let timeWord = "Ago"
let dateObj = new Date();
// this is to set the appropriate seconds, minutes and hours
if (currentDate == previousDate) {
if (dateObj.getHours() == previousHours) {
if (dateObj.getMinutes() == previousMinutes) {
timeInNumber = dateObj.getSeconds() - previousSeconds;
timePeriod = "Second";
} else {
timeInNumber = dateObj.getMinutes() - previousMinutes;
timePeriod = "Minute";
}
} else {
timeInNumber = dateObj.getHours() - previousHours;
timePeriod = "Hour";
// timePeriod =dateObj.getHours();
}
}
else {
const previousDateDifferential = new Date(previousDate);
const currentDateDifferential = new Date(currentDate);
const diffrenceInDate = Math.abs(
currentDateDifferential - previousDateDifferential
);
// this is to calculate the diffrence in days, weeks, months and years
const diffDays = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24));
const diffWeeks = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7));
const diffMonths = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4));
const diffyears = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4 * 12));
// this is to set the appropriate days, weeks, months and years
if (diffDays <= 30) {
timeInNumber = diffDays;
timePeriod = "Day";
} else if (diffDays > 30 && diffWeeks <= 4) {
timeInNumber = diffWeeks;
timePeriod = "Week";
} else if (diffWeeks > 4 && diffMonths <= 12) {
timeInNumber = diffMonths - 2;
timePeriod = "Month";
} else if (diffMonths > 12) {
timeInNumber = diffyears - 1;
timePeriod = "Year";
}
if (currentDate < previousDate) {
timeWord = "Later"
}else {
timeWord = "Ago"
}
}
if (timeInNumber > 1) {
timePeriod += "s"// this is to ad 's' at the end of the time period if the time period is more than 1
}
return `${timeInNumber} ${timePeriod} ${timeWord}`;
}
GetDateDiff("05/14/2022", "00:00:00") // result will be 2 days ago
GetDateDiff("05/18/2022", "00:00:00") // result will be 2 days later

How to return HTML tag from javascript?

I have a list of data displayed using ng-repeat.
I'm thinking that if it is possible to return HTML tag, it would be easier.
Like this:
return '<span class="redHour">'+diffHours+'</span>;
but this does't work.
I have this HTML code:
<li><p class="table-data3" id="normal-hour">{{RT(order.purchaseTime)}}</p> </li>
If the calculated purchase time is less than 4 I want the color of the p becomes red.
Function
$scope.RT = function(order) {
var timeDifference;
var currentDate;
var deadLine;
var diffDays;
var diffHours;
var diffMinutes;
currentDate = new Date();
deadLine = new Date(parseInt(order)); // setting purchase time Date Object
deadLine = new Date(deadLine.setDate(deadLine.getDate()+1)); // setting purchase time Date Object + 1 day
timeDifference = (deadLine.getTime()) - (currentDate.getTime()); // deadline data minus current date
var diffDays = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
var diffHours = Math.floor(timeDifference / (1000 * 60 * 60));
var diffMinutes = Math.floor((timeDifference-(diffHours*(1000 * 60 * 60))) / (1000 * 60));
if(diffHours <= 4){
//WHAT SHOULD I PUT HERE?
}
if (diffHours == 0 && diffMinutes > 0) {
return diffMinutes +" Mins";
}else if (diffHours <= 0) {
diffHours = 0;
return diffHours;
}else if (diffHours == 1) {
return diffHours + " Hour";
}else {
return diffHours +" Hours";
}
}
THANK YOU!
You can implement filter:
app.filter('hoursNow', function () {
return function (ts) {
var timeDifference = Date.now() - ts;
var diffDays = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
var diffHours = Math.floor(timeDifference / (1000 * 60 * 60));
var diffMinutes = Math.floor((timeDifference-(diffHours*(1000 * 60 * 60))) / (1000 * 60));
if (diffHours < 4) {
return '<span class="red">'+diffHours+'hrs</span>';
}
return '<span class="green">'+diffHours+'hrs</span>';
}
});
And use it with ng-bind-html:
<p ng-bind-html="order.purchaseTime | hoursNow"></p>
Fiddle
Your $scope.RT function could return a CSS class and the value itself. You can add the CSS class to the p tag in your template to change the styling according to the value.
Modify your method to return object and use ngInit directive. Your method can return Object with properties {'text': String, 'display_red': Boolean}.
<div ng-repeat="item in date" ng-init="item_info = RT(item.purchaseTime)">
<li ng-class="{inRed: item.displayRed}">
<span class="table-data3" id="normal-hour">{{item.text}}</span>
</li>
</div>
Also I've used ngClass directive to dynamically assign css class inRed, so you have to add such css class to.
Also below is modified if..else from $scope.RT function:
var result = {'displayRed': False};
if(diffHours <= 4){
result['displayRed'] = True;
}
if (diffHours == 0 && diffMinutes > 0) {
result['text'] = diffMinutes +" Mins";
}else if (diffHours <= 0) {
diffHours = 0;
result['text'] = diffHours;
}else if (diffHours == 1) {
result['text'] = diffHours + " Hour";
}else {
result['text'] = diffHours +" Hours";
}
return result
use ng-style in your DOM
<li><p class="table-data3" id="normal-hour" ng-style="setColor(order)">{{RT(order.purchaseTime)}}</p> </li>
in controller
$scope.setColor = function(order){
var color;
//Do your math
return{ 'background-color': color}
}

replace zero(integer) with space(string) with javascript

I am calculating age from DOB but while i am returning value it show '0' for more see below code
var birth = new Date('DOB');
var curr = new Date();
var age; // this is integer type in database
if(birth != null)
{
var diff = curr - birth;
age= Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
} else {
age=' '; // while i return space from here it shows '0' on my output
}
How i can show space insted of '0'
replace it 'null' to null. null it is not string.
var curr = new Date();
var age; // this is integer type in database
if(R2 != null && R2 != undefined )
{
var diff = curr - birth;
AGE= Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}else
AGE=' '; // while i return space from here it shows '0' on my output
}
I did as little modification to your code as I could to not modify it's structure. The main change is to check if age is zero or less than zero, because the original code did return 0 or even negative numbers if the birth date was in the last year or in the future. This should work.
var birth = new Date('DOB');
var curr = new Date();
var age; // this is integer type in database
if (birth != null)
{
var diff = curr - birth;
age = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
if (age < 1) {
age = ' ';
}
} else {
age = ' '; // while i return space from here it shows '0' on my output
}

JS Time elapsed since a date

I'd like to calculate the elapsed time between two dates. I saw some examples on the internet (most of them on this site), but found nothing useful. I'd like to write a function can call like this:
calculateDifference('2012-02-01 15:31')
There is no second parameter, since it is the current date. I have a code I'm currently using, which is:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (date_diff.getHours() > 0) {
respvalue += (date_diff.getHours() - 1) + " hour(s) and ";
}
respvalue += date_diff.getMinutes() + " minute(s) ago.";
return respvalue;
}
And the result is and should be:
1 day(s), 14 hour(s) and 17 minute(s)
For some reasons there are differences (when 1 day passed it shows 0 etc) and it works only with chrome, in IE and FF it returns with the date I passed as the parameter.
Once again: I'd like to calculate the difference between the current date and a given date in the next format:
1 day(s), 14 hour(s) and 17 minute(s)
I don't care about the months, years. Only hours, mins and secs. Thank you in advance!
Try this:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var hours = Math.floor(milisec_diff / (1000 * 60 * 60) - days * 24);
var minutes = Math.floor(milisec_diff / (1000 * 60) - days * 24 * 60 - hours * (60));
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (hours > 0) {
respvalue += hours + " hour(s) and ";
}
respvalue += minutes + " minute(s) ago.";
return respvalue;
}
The problem is that your date format is not valid, so Firefox can't parse your strings as dates.
You can use
function get_time_diff(datetime) {
var milisec_diff = Math.abs(new Date() - new Date(datetime)),
diff = new Date(milisec_diff),
days = milisec_diff / 3600e3 / 24 | 0,
hours = diff.getUTCHours(),
respvalue = '';
if (days)
respvalue += days + " day(s), ";
if (hours)
respvalue += hours + " hour(s) and ";
respvalue += diff.getUTCMinutes() + " minute(s) ago.";
return respvalue;
}
get_time_diff('2012-02-01T15:31Z');
Where the date 2012-02-01T15:31Z is in ISO8601, and the Z means UTC time (note some browsers may not support it).
This seems simplest to me:
http://jsbin.com/tusul/9/edit
// end date is optional, it will assume the current date if not supplied.
// if timezone is not supplied, it will assume local browser time.
function calculateDateDiff(beginDate, endDate) {
var currentDate;
if (typeof(endDate) == 'undefined') {
currentDate = new Date();
} else {
currentDate = new Date(endDate);
}
var targetDate = new Date(beginDate);
var differenceDate;
if (currentDate > targetDate) {
differenceDate = new Date(currentDate - targetDate);
} else {
differenceDate = new Date(targetDate - currentDate);
}
return('Days: ' + (differenceDate.getUTCDate() -1) + ', Hours: ' + differenceDate.getUTCHours() + ', Minutes: ' + differenceDate.getUTCMinutes() + ', Seconds: ' + differenceDate.getUTCSeconds());
}
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04'));
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04Z'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03-500', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03+1000', '05-22-2014 02:03:04-600'));

Categories

Resources