I have written a code to calculate the age of content on a website. It's inefficient, and the calculations are way off. I've written this script before, and last time it worked perfectly, but I can't find the damn file it's in.
I think the calculation problem is caused by the year. Can anyone suggest a fix up for me? Created date format is YYYYMMDD and output is in whole weeks (this is important), i.e. the example below should output '52' weeks.
var created='20120223';
var year=Number(created.substr(0,4));
var month=Number(created.substr(4,2))-1;
var day=Number(created.substr(6,2));
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var input_age = ((((curr_year - year)*31536000) + ((curr_month - month)*2678400) + ((curr_date - day)*86400))/604800).toFixed(0);
document.getElementById('item12345_input').value = input_age + ' weeks';
you are subtracting a month first. then you are again adding a month. try this
var created='20120223';
var year=Number(created.substr(0,4));
var month=Number(created.substr(4,2))-1;
var day=Number(created.substr(6,2));
var d = new Date();
var curr_date = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var input_age = ((((curr_year - year)*31536000) + ((curr_month - month)*2678400) + ((curr_date - day)*86400))/604800).toFixed(0);
alert(input_age + ' weeks');
Note Months are 0 based
<script>
var created ="20120223";
var yyyy = +created.substring(0, 4);
var mm = created.substring(4, 6)-1;
var dd = +created.substring(6, 8);
var createdDate = new Date(yyyy,mm,dd);
var ageMillis = new Date().getTime() - createdDate.getTime();
var MS_PER_WEEK = 1000/* ms /sec */
* 60 /* sec/min */
* 60 /* min/hr */
* 24 /* hr /day */
* 7 /* day/wk */;
var ageWeeks = parseInt(ageMillis / MS_PER_WEEK);
alert("Created on " +mm+"/"+dd+"/"+yyyy+" which is "+ageWeeks+ " week"+(ageWeeks==1?"":"s")+" ago");
</script>
you could try this:
var created='20120223';
var year=Number(created.substr(0,4));
var month = Number(created.substr(4,2));
if (Number(created.substr(4,2)) < 10){
month = '0'+ Number(created.substr(4,2));
}
var day=Number(created.substr(6,2));
var dt = year+'-'+month+'-'+day;
var dif = new Date().getTime() - Date.parse(dt);
var divWeek = 7 * 24 * 60 * 60 * 1000;
alert(Math.round(dif/divWeek));
Just subtract the 2 dates.
var createdDate = new Date(
+created.substring(0, 4), // Four digit year
created.substring(4, 6)-1, // Base-zero month
+created.substring(6, 8)); // Day of month
var ageMillis = (new Date) - createdDate;
var MS_PER_WEEK = 1000/* ms /sec */
* 60 /* sec/min */
* 60 /* min/hr */
* 24 /* hr /day */
* 7 /* day/wk */;
var ageWeeks = ageMillis / MS_PER_WEEK;
Related
I have a date like this 2017-07-25 09:30:49, when I subtract 2017-07-25 10:30:00 and 2017-07-25 09:30:00, I need a result like 1 Hours.
I can't find correct search key for googling what I need.
Anyone know what should I search on google ? or someone knows some function about that?
PS. Mysql or Javascript
Try with date object in javascript
Like this
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:49")
var diff = Math.abs(d1-d2); // difference in milliseconds
Then convert the milliseconds to hours
var hours = parseInt((diff/(1000*60*60))%24);
You can go through it
Get the time difference between two datetimes
But the query is not clear do you want only the hour difference or you want the difference converted to hour format
Like what it will give if 2017-07-25 09:30:49 and 2017-07-26 10:30:00 ? 25 hour or 1 hour?
here a code example of how to do it
var date1 = new Date("2017-07-25 09:30:49");
var date2 = new Date("2017-07-25 10:30:00");
var datesum = new Date(date1 - date2);
var hours = datesum.getHours();
var minutes = datesum.getMinutes();
var seconds = datesum.getSeconds();
console.log(hours + " hour, " + minutes + " minutes, " + seconds + " seconds" )
var dateString = "2017-07-25 09:30:49";
var dateString2= "2017-07-25 11:30:00";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString);
var dateArray2= reggie.exec(dateString2);
var dateObject1= new Date(
(+dateArray[1]),
(+dateArray[2])-1, // Careful, month starts at 0!
(+dateArray[3]),
(+dateArray[4]),
(+dateArray[5]),
(+dateArray[6])
);
var dateObject2= new Date(
(+dateArray2[1]),
(+dateArray2[2])-1, // Careful, month starts at 0!
(+dateArray2[3]),
(+dateArray2[4]),
(+dateArray2[5]),
(+dateArray2[6])
);
var diff = Math.abs(dateObject2-dateObject1); // difference in milliseconds
var hours = parseInt((diff/(1000*60*60))%24);
Try with the below dateFormatter function :
var d1 = new Date("2017-07-25 10:30:00");
var d2 = new Date("2017-07-25 09:30:00")
var diff = Math.abs(d1-d2);
var d = dateFormatter(diff);
console.log(d);
function dateFormatter(t){
var cd = 24 * 60 * 60 * 1000;
var ch = 60 * 60 * 1000;
var cm = 60*1000;
var d = Math.floor(t / cd);
var h = '0' + Math.floor( (t - d * cd) / ch);
var m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
var s = '0' + Math.round((t - (d * cd) - (h * ch) - (m * cm))/1000);
return d + " days, " + h.substr(-2) + " hours, " + m.substr(-2) + " minutes, " +s.substr(-2)+ " seconds";
}
****Salary type monthly.****
var getDiffDatesSalary = function days_between(date1,date2, monthlyBasic) {
var dateObj1 = new Date(date1);
var month1 = dateObj1.getMonth(); //months from 1-12
var day1 = dateObj1.getDate();
var year1 = dateObj1.getFullYear();
var daysInMonth1 = Date.getDaysInMonth(year1, month1);
var dateObj2 = new Date(date2);
var month2 = dateObj2.getMonth(); //months from 0-11
var day2 = dateObj2.getDate();// days from 1
var year2 = dateObj2.getFullYear();
var daysInMonth2 = Date.getDaysInMonth(year2, month2);
var date1FractionDays = daysInMonth1 - day1;
var date2FractionDays = daysInMonth2 - day2;
var newDate1, newDate2;
if(day1 > 1){
var perDaySalary1 = monthlyBasic / daysInMonth1;
var thisMonthFarctionDaysSalaryForDate1 = perDaySalary1 * date1FractionDays;
month1 += 1; // after calculate fraction this month basic, round month from next
newDate1 = new Date(year1,month1);
}
if(day2 !== daysInMonth2){
var perDaySalary2 = monthlyBasic / daysInMonth2;
var thisMonthFarctionDaysSalaryForDate2 = perDaySalary2 * day2;
month2 -= 1; //after calculate fraction this month basic, round month from previous
newDate2 = new Date(year2,month2);
}
// i want to calculate totalSalaryamount of date ranges
// var totalFractionDaysSalary = thisMonthFarctionDaysSalaryForDate1 + thisMonthFarctionDaysSalaryForDate2;
// var totalMonthsSalay = roundMonths * monthlyBasic;
// var totalSalaryamount = totalFractionDaysSalary + totalMonthsSalay;
};
**
result = thisMonthFarctionDaysSalaryForDate1 + thisMonthFarctionDaysSalaryForDate2 + (roundMonths * monthlyBasic)
result will be getDiffDatesSalary("2016/01/15","2016/03/25", 1000);
516.13+806.45 + 1000 // total: 2322.58
Or/And getDiffDatesSalary("2015/01/15","2016/03/25", 1000) ;
516.13+806.45 + (1000 * 13) // total: 14322.58
Or/And getDiffDatesSalary("2016/01/01","2016/02/29", 1000);
1000* 2 // 2000
**
I suggest to split the task in two sections:
Get total days
Calculate salary.
This proposal uses the difference between years, months and days and makes a correction if the day difference is negative. Same day means one day.
function getDays(date1, date2) {
var date1Obj = new Date(date1),
date2Obj = new Date(date2),
totalYear = date2Obj.getFullYear() - date1Obj.getFullYear(),
totalMonth = date2Obj.getMonth() - date1Obj.getMonth(),
totalDay = date2Obj.getDate() - date1Obj.getDate() + 1;
if (totalDay < 0) {
totalMonth--;
totalDay += new Date(date1Obj.getFullYear(), date1Obj.getMonth(), 0).getDate();
}
return 360 * totalYear + 30 * totalMonth + totalDay;
}
function getDiffDatesSalary(date1, date2, salaryPerMonth) {
return getDays(date1, date2) * salaryPerMonth / 30;
}
document.write(getDiffDatesSalary("2016/01/15", "2016/03/25", 1000) + '<br>');
document.write(getDiffDatesSalary("2016/01/31", "2016/02/15", 1000) + '<br>');
document.write(getDiffDatesSalary("2016/03/20", "2016/03/20", 3000) + '<br>');
I got the answer of my question. If anyone need or improve this answer. Here is the working codes:
var getDiffDatesSalary = function days_between(date1,date2, monthlyBasic) {
var dateObj1 = new Date(date1);
var month1 = dateObj1.getMonth(); //months from 0-11
var day1 = dateObj1.getDate();
var year1 = dateObj1.getFullYear();
var daysInMonth1 = Date.getDaysInMonth(year1, month1);
var dateObj2 = new Date(date2);
var month2 = dateObj2.getMonth(); //months from 0-11
var day2 = dateObj2.getDate();// days from 1
var year2 = dateObj2.getFullYear();
var daysInMonth2 = Date.getDaysInMonth(year2, month2);
//get number of months in two different dates;
var diffMonths = parseInt(diffInMonths(date2,date1)) +1; //from 1-12
var date1FractionDays = daysInMonth1 - day1; // date1 fraction days
var date2FractionDays = daysInMonth2 - day2; // date2 fraction days
var totalFractionDaysSalary= 0, fractionMonthsCount = 0, thisMonthFarctionDaysSalaryForDate1 = 0, thisMonthFarctionDaysSalaryForDate2 =0; //reset as 0;
//when date1: day start from 01, no fraction start of the month. Otherwise calculate salary for fraction days
if(day1 > 1){
var perDaySalary1 = monthlyBasic / daysInMonth1;
thisMonthFarctionDaysSalaryForDate1 = perDaySalary1 * date1FractionDays;
fractionMonthsCount +=1;
}
//when date2: day end === end Of the Month, no fraction. Otherwise calculate salary for fraction days
if(day2 !== daysInMonth2){
var perDaySalary2 = monthlyBasic / daysInMonth2;
thisMonthFarctionDaysSalaryForDate2 = perDaySalary2 * day2;
fractionMonthsCount +=1;
}
// both date1 date2 fraction days salary sum
totalFractionDaysSalary = thisMonthFarctionDaysSalaryForDate1 + thisMonthFarctionDaysSalaryForDate2;
var roundMonthsForSalary = diffMonths - fractionMonthsCount; // after less round month calculate
// if user do wrong reset as 0. because negative month not possible
if (roundMonthsForSalary < 0){
roundMonthsForSalary = 0;
}
// round month salary calculation
var totalSalaryForRoundMonths = roundMonthsForSalary * monthlyBasic;
// finally fraction days and round month sum to get return result.
return totalFractionDaysSalary + totalSalaryForRoundMonths;
};
// get number of months in two different dates
function diffInMonths(to,from){
var months = to.getMonth() - from.getMonth() + (12 * (to.getFullYear() - from.getFullYear()));
if(to.getDate() < from.getDate()){
var newFrom = new Date(to.getFullYear(),to.getMonth(),from.getDate());
if (to < newFrom && to.getMonth() == newFrom.getMonth() && to.getYear() %4 != 0){
months--;
}
}
return months;
};
Hi I am trying to get the difference between two dates but I keep on getting 0 as the answer anyone knows why please help. My code is like this
var d1 = "2015-04-30";
var d2 = "2015-04-14";
var startDay = new Date(d1);
var endDay = new Date(d2);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = startDay.getTime() - endDay.getTime();
var days = millisBetween / millisecondsPerDay;
//If I use df1 and df2 I am getting 0
var jsondate1 = new Date(getData.startDate).toISOString();
var jsondate2 = new Date(getData.startDate).toISOString();
var date = new Date(jsondate1);
var dates = new Date(jsondate2);
var df1 = date.getFullYear() + '-' + (date.getMonth()+1) + '-'
+date.getDate() ;
var df2 = dates.getFullYear() + '-' +(dates.getMonth()+1)
+ '-' +dates.getDate() ;
//If I am using the below two lines the answer is 16 but if I am using the above d1 and d2 the answer is zero
var d1 = "2015-4-30";// the date here is made up by console.debug(df1 )
var d2 = "2015-4-14"; // the date here is made up by console.debug(df2 )
I don't know where am I doing wrong
See the snippet - It shows 16.
var d1 = "2015-04-30";
var d2 = "2015-04-14";
var startDay = new Date(d1);
var endDay = new Date(d2);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = startDay.getTime() - endDay.getTime();
var days = millisBetween / millisecondsPerDay;
alert(days);
I think you should check your code at your end , because it's working as you want but some code syntax mistake will be there in your code. (may be)
It should work as is but you can try subtracting the dates without calling getTime():
var d1 = "2015-04-30";
var d2 = "2015-04-14";
var startDay = new Date(d1);
var endDay = new Date(d2);
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = startDay - endDay;
var days = millisBetween / millisecondsPerDay;
alert(days);
After question update:
Both jsondate1 & jsondate2 are being created using the same date (getData.startDate), hence the difference is 0:
var jsondate1 = new Date(getData.startDate).toISOString();
var jsondate2 = new Date(getData.startDate).toISOString();
If you want date difference only. Then easiest way to do is.
var d1 = "2015-04-30";
var d2 = "2015-04-14";
Math.floor(( Date.parse(d1) - Date.parse(d2) ) / 86400000);
I have a function that will calculate time between two date / time but I am having a small issue with the return.
Here is the way I collect the information.
Start Date
Start Time
Ending Date
Ending Time
Hours
And here is the function that calculates the dates and times:
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var sec = date2.getTime() - date1.getTime();
if (isNaN(sec)) {
alert("Input data is incorrect!");
return;
}
if (sec < 0) {
alert("The second date ocurred earlier than the first one!");
return;
}
var second = 1000,
minute = 60 * second,
hour = 60 * minute,
day = 24 * hour;
var hours = Math.floor(sec / hour);
sec -= hours * hour;
var minutes = Math.floor(sec / minute);
sec -= minutes * minute;
var seconds = Math.floor(sec / second);
var min = Math.floor((minutes * 100) / 60);
document.getElementById("result").value = hours + '.' + min;
}
If I put in todays date for both date fields and then 14:30 in the first time field and 15:35 in the second time field the result is shown as 1.8 and it should be 1.08
I didn't write this function but I am wondering if someone could tell me how to make that change?
Thank you.
If I understand correctly, the only issue you are having is that the minutes are not padded by zeroes. If this is the case, you can pad the value of min with zeroes using this little trick:
("00" + min).slice(-2)
I can't see why 15:35 - 14:30 = 1.08 is useful?
Try this instead:
function timediff( date1, date2 ) {
//Get 1 day in milliseconds
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 = date2_ms - date1_ms;
//take out milliseconds
difference_ms = difference_ms/1000;
var seconds = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var minutes = Math.floor(difference_ms % 60);
difference_ms = difference_ms/60;
var hours = Math.floor(difference_ms % 24);
var days = Math.floor(difference_ms/24);
return [days,hours,minutes,seconds];
}
function calculate (form) {
var d1 = document.getElementById("date1").value;
var d2 = document.getElementById("date2").value;
var t1 = document.getElementById("time1").value;
var t2 = document.getElementById("time2").value;
var dd1 = d1 + " " + t1;
var dd2 = d2 + " " + t2;
var date1 = new Date(dd1);
var date2 = new Date(dd2);
var diff = timediff(date1, date2);
document.getElementById("result").value = diff[1] + ':' + diff[2];
}
Verify if number of minutes is less than 10 and if it is then append an additional zero in front. Follow similar approach for seconds.
I am getting the values from two text fields as date
var start_actual_time = $("#startPoint_complete_date").val();
var end_actual_time = $("#endPoint_complete_date").val();
which gives value
start_actual_time = 01/17/2012 11:20
end_actual_time = 01/18/2012 12:20
now i want to find out the duration in HH:MM format between these two dates (which is 25:00 in this case)
how can i do it...
var start_actual_time = "01/17/2012 11:20";
var end_actual_time = "01/18/2012 12:25";
start_actual_time = new Date(start_actual_time);
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time - start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
alert(formatted);
See demo : http://jsfiddle.net/diode/nuv7t/5/ ( change mootools in jsfiddle
or open http://jsfiddle.net/nuv7t/564/ )
Working example:
gives alert message as 6:30
$(function(){
var startdate=new Date("01/17/2012 11:20");
var enddate=new Date("01/18/2012 12:20");
var diff = new Date(enddate - startdate);
alert(diff.getHours()+":"+diff.getMinutes());
});
First, I recommend this: http://www.mattkruse.com/javascript/date/ to convert the string to a date object, but you can convert it any way you want. Once converted, you can do this:
var difference_datetime = end_datetime.getTime() - start_datetime.getTime()
The getTime() function gets the number of milliseconds since 1970/01/01. Now you have the number of milliseconds of difference, and you can do whatever you want to convert to higher numbers (eg. divide by 1000 for seconds, divide that by 60 for minutes, divide that by 60 for hours, etc.)
I did something simular on a blog to see how long im together with my gf :P
http://daystogether.blogspot.com/ and this is how I did it:
// *****Set the unit values in milliseconds.*****
var msecPerMinute = 1000 * 60;
var msecPerHour = msecPerMinute * 60;
var msecPerDay = msecPerHour * 24;
// *****Setting dates*****
var today = new Date();
var startDate = new Date('10/27/2011 11:00:00');
// *****Calculate time elapsed, in MS*****
var interval = today.getTime() - startDate.getTime();
var days = Math.floor(interval / msecPerDay );
interval = interval - (days * msecPerDay );
var weeks = 0;
while(days >= 7)
{
days = days - 7;
weeks = weeks + 1;
}
var months = 0;
while(weeks >= 4)
{
weeks = weeks - 4;
months = months + 1;
}
// Calculate the hours, minutes, and seconds.
var hours = Math.floor(interval / msecPerHour );
interval = interval - (hours * msecPerHour );
var minutes = Math.floor(interval / msecPerMinute );
interval = interval - (minutes * msecPerMinute );
var seconds = Math.floor(interval / 1000 );
BTW this is just javascript, no jquery ;)
here you go:
function get_time_difference(start,end)
{
start = new Date(start);
end = new Date(end);
var diff = end.getTime() - start.getTime();
var time_difference = new Object();
time_difference.hours = Math.floor(diff/1000/60/60);
diff -= time_difference.hours*1000*60*60;
if(time_difference.hours < 10) time_difference.hours = "0" + time_difference.hours;
time_difference.minutes = Math.floor(diff/1000/60);
diff -= time_difference.minutes*1000*60;
if(time_difference.minutes < 10) time_difference.minutes = "0" + time_difference.minutes;
return time_difference;
}
var time_difference = get_time_difference("01/17/2012 11:20", "01/18/2012 12:20");
alert(time_difference.hours + ":" + time_difference.minutes);
start_date.setTime(Date.parse(start_actual_time));
end_date.setTime(Date.parse(end_actual_time));
//for check
start_date.toUTCString()
end_date.toUTCString()
/**
* Different in seconds
* #var diff int
*/
var diff = (end_date.getTime()-start_date.getTime())/1000;