Date Difference, how many H D M Y have passed - javascript

I am building an Instagram feed with JQuery into my site and want to show how long has passed since the post was submitted in a short form like: 23H or 2D or 3M or 1Y depending on how long its been. I've got my two date objects but I can't figure our how to calculate the difference and display it how i want.
I am fairly new to JS/Jquery and as far as i could get was:
var pd = new Date(postDate);
var nd = new Date();
var nd = nd.getTime();
var difference = nd-pd;
How do I calculate the difference between two dates in hours, days, months and years?
Thanks.

Doing anything with dates is generally painful.
If you aren't committed to using that exact format, you can use a library for this instead.
moment.js has a .fromnow() function.
or timeago.js can be used to update the element on the page periodically, so if the user leaves the page open for a few minutes, the time stamps will count up.

You can do this to get the time elapsed since posted
var timeDiff = Math.abs(nd.getTime() - pd.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));

you can try like this.
var pd = new Date(postDate);
var nd = new Date();
var Hours = nd.getHours() - pd.getHours();
var Days = nd.getDay() - pd.getDay();
var Months = nd.getMonth() - pd.getMonth();
var Years = nd.getYear() - pd.getYear();
or get millisecods diference
var miliseconds = (nd - pd).getTime(); //gets time in miliseconds since 1/1/1970
then use your logic to calculate hours, days, months and years
you can have a look at this Work with a time span in Javascript
moments
ar date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");

My solution is dirty but direct: calculate them by myself.
Record start time:
var BEGIN_TIME=new Date();
var HOUR=BEGIN_TIME.getHours();
var MINUTE=BEGIN_TIME.getMinutes();
var SECOND=BEGIN_TIME.getSeconds();
Then do so some math
var today=new Date();
h=today.getHours();
m=today.getMinutes();
s=today.getSeconds();
s = s - SECOND;
if (s<0) { s=s+60; m=m-1; }
m = m - MINUTE;
if (m<0) { m=m+60; h=h-1; }
h = h - HOUR;

Related

Convert Javascript Date object to Excel serial date number

So I have a Javascript date object with year, month, days, hours, minutes, seconds, and milliseconds data and I need to convert this object to an Excel serial number but I didn't find a way to do that.
I found how to convert only a Date object but the way I found didn't consider the time part.
Any suggestions?
Thank you,
Regards.
finally I was able to convert it properly, I used the following code to do so:
let date = new Date();
let converted = 25569.0 + ((date.getTime() - (date.getTimezoneOffset() * 60 * 1000)) / (1000 * 60 * 60 * 24));
Thank you all.
Try this:
function ExcelDateToJSDate(serial) {
var utc_days = Math.floor(serial - 25569);
var utc_value = utc_days * 86400;
var date_info = new Date(utc_value * 1000);
var fractional_day = serial - Math.floor(serial) + 0.0000001;
var total_seconds = Math.floor(86400 * fractional_day);
var seconds = total_seconds % 60;
total_seconds -= seconds;
var hours = Math.floor(total_seconds / (60 * 60));
var minutes = Math.floor(total_seconds / 60) % 60;
return new Date(date_info.getFullYear(), date_info.getMonth(), date_info.getDate(), hours, minutes, seconds);
}
Or you can use:
function SerialDateToJSDate(serialDate) {
var days = Math.floor(serialDate);
var hours = Math.floor((serialDate % 1) * 24);
var minutes = Math.floor((((serialDate % 1) * 24) - hours) * 60)
return new Date(Date.UTC(0, 0, serialDate, hours-17, minutes));
}

Countdown Timer - Timezone Issues

I was following this tutorial: https://www.w3schools.com/howto/howto_js_countdown.asp
And everything works except for timezones, I want it to show the same time on every device, no matter the timezone, in UTC. How would I go about this?
If someone in a timezone was ahead of me, they would see a different time (because they are an hour ahead, so the countdown would end at a different time. It would end for them an hour ahead of when it ends for me, I want the same time on the timer to be shown everywhere
Code (Edited):
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
function getUTCNow() {
var now = new Date();
var time = now.getTime();
var offset = now.getTimezoneOffset();
offset = offset * 60000;
return time - offset;
}
// Set the date we're counting down to
//var countDownDate = new Date("Sep 15, 2018 15:00:00").getTime();
var countDownDate = new Date("Sep 7, 2018 20:00:00");
var countDD = convertDateToUTC(countDownDate);
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date();
var nowUTC = now.getUTCTime();
// Find the distance between now and the count down date
var distance = countDD.getTime() - nowUTC.getTime();
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="timer"
document.getElementById("timer").innerHTML = days + "d " + hours + "h " +
minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("timer").innerHTML = "RELEASED!";
}
}, 1000);
<div id="timer"></div>

Get closest date to current date (javascript)

So I have an array of dates and want to get the current date and put it into a countdown clock
I have this code atm:
<script>
var dates = [
'24/5/2017',
'12/6/2017',
'14/6/2017',
'16/6/2017',
'20/6/2017',
'20/6/2017',
'22/6/2017',
'23/6/2017',
'26/6/2017'
];
function sortDates(dates) {
return dates.map(function(date) {
return new Date(date).getTime();
}).sort(function(a, b) {
return a - b;
});
}
var orderedDates = sortDates(dates);
document.getElementById("demoo").innerHTML = orderedDates
var nextDate = orderedDates.filter(function(date) {
return (var now = new Date().getTime(); - date) > 0;
})[0];
document.getElementById("demo").innerHTML = nextDate
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = nextDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
<center><h2>Core Maths 2</h2><center>
This doesn't seem to do anything, so I don't really know what to do. at the moment it just comes up with NAN for the countdown
One problem is, that, for instance, new Date('24/5/2017') yields Invalid Date. I don't think this is a valid Date format recognized by new Date().
If you really need the format like this, you can do something like:
var dates = [
'24/5/2017', // past Date for testing
'12/6/2017',
'14/6/2017',
'16/6/2017',
'20/6/2017',
'20/6/2017',
'22/6/2017',
'23/6/2017',
'26/6/2017'
].map(function (d) {
var parts = d.split('/');
return new Date(parts[2], parts[1] - 1 /* january = 0 */, parts[0]);
});
so you end up having actual Date objects instead of strings by passing the parameters in a order to the Date constructor which it understands.
Another point: Since you can interpret a Date object as a Number (which yields the same as new Date().getTime(), namely the milliseconds since January 1, 1970), you can simply get the minimum using: Math.min.apply(Math, dates). So, your "next Date" (smallest timestamp which is not in the past) can simply been retrieved by var nextDate = new Date(Math.min.apply(Math, dates.filter(x => +x > Date.now())));
Below is a working snipppet which should do what you wanted.
var dates = [
'20/4/2017',
'24/5/2017',
'12/6/2017',
'14/6/2017',
'16/6/2017',
'20/6/2017',
'20/6/2017',
'22/6/2017',
'23/6/2017',
'26/6/2017'
].map(function (d) {
var parts = d.split('/');
return new Date(parts[2], parts[1] - 1 /* january = 0 */, parts[0]);
});
var nextDate = new Date(Math.min.apply(Math, dates.filter(x => +x > Date.now())));
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = nextDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<center><h2>Core Maths 2</h2><center>
<div id="demo"></div>
So I did your dirty work for you, all you needed to do is some debugging, putting some console logs here and there to find out what was going wrong, which was a couple of things.
1. Your date formats are messed up (at least for me).
Instead of typing '24/5/2017', type '5/24/2017' if you want it to go right when you pass it into a Date() constructor. You can validate this by doing this: console.log(new Date('24/5/2017'));
2. Your filter function was bad
You want the next date, though you check for now - date > 0 which means that only dates that were in past will work. Either use date - now > 0 or now - date < 0.
3. You made a typo
document.getElementById("demoo").innerHTML = orderedDates
Notice the extra 'o' in 'demoo'.
4. You used invalid syntax
var nextDate = orderedDates.filter(function(date) {
return (var now = new Date().getTime(); - date) > 0;
})[0];
This doesn't work because you cannot declare now like this. Extract the declaration of now to a line above the return statement as follows:
var nextDate = orderedDates.filter(function(date) {
var now = new Date().getTime();
return (now - date) < 0;
})[0];
If you apply all these corrections your countdown should work.

Calculate date difference using javascript

How to calculate the time difference using jquery?
Example:
First 4 hours is equivalent to 0.5
Whole day is equivalent to 1.0
Example working hours
8am to 12pm is 0.5
1pm to 5pm will equivalent to 0.5 also.
and 24 hours is equivalent to 1.0
for example:
11/11/2014 08:00am 11/11/2014 12:00pm
result is 0.5..
Thanks
$('#get').click(function(){
var startDate = new Date($('#dpd1').val());
var startTime =(''+ $("#time1").val()).split(":");
var endDate = new Date($('#dpd2').val());
var endTime = (''+ $("#time2").val()).split(":");
startDate.setHours(parseInt(startTime[0]));
startDate.setMinutes(parseInt(startTime[1]));
endDate.setHours(parseInt(endTime[0]));
endDate.setMinutes(parseInt(endTime[1]));
var diff = endDate.getTime() - startDate.getTime();
var differenceDays = (diff) / (1000 * 60 * 60 * 24);
var differenceHours = ((diff) % (1000 * 60 * 60 * 24))/ (1000 * 60 * 60);
$('#totalleave').val(Math.round(differenceDays) + ' days ' +Math.round(differenceHours) + ' hours' );
});
var date1 = new Date(d1), date2 = new Date(date2);
var hourDiff = date1.getHours()-date2.getHours();
now manipulate this hourDiff the way you want.

Convert Date to number (not timestamp) in javascript

I am looking for a way to convert a javascript Date to a number that represents the amount of days passed since , for example, 1.1.1900, for that date. As it is usually done with timestamps and miliseconds.
Can I do this?
You can achieve this by using the javascript function getTime().
Code:
var a = new Date();
alert(a.getTime());
Working Example
According to getTime() definition:
The getTime() method returns the numeric value corresponding to the
time for the specified date according to universal time.
More can be found in this link
UPDATE:
If you want to have it in no of days then you would need to calculate it or use library like moment.js
Working Fiddle for Days
For example something like:
var date1 = new Date("1/Jan/1900 00:00:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");

Categories

Resources