How to get time difference between two timestamps in seconds with jQuery? - javascript

I want to display x seconds ago based on a MySQL Timestamp.
I found the plugin called timeago
But I cannot find a way to make it display only seconds.
I'm OK with 61 seconds, or 300 seconds. Any way to convert the output to seconds with timeago, or with pure jQuery / JavaScript ?
Thanks for any help !
Edit:
Sample Case :
$time1 = "2014-02-02 23:54:04"; // plus PHP ways to format it.
//$time2 = NOW() , or date(); whatever.
I just want to get how many seconds since $time1.
Edit 2:
Working code :
<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/100).toString());
// note that you may want to round the value
});
</script>
It outputs Diff. Seconds : NaN

assuming you parse the string into JavaScript date object, you can do
(date2 - date1)/1000
to parse mysql format timestamp, just feed the string into new Date():
var d2 = new Date('2038-01-19 03:14:07');
var d1 = new Date('2038-01-19 03:10:07');
var seconds = (d2- d1)/1000;
fix of edit 2 in the question:
<script type="text/javascript">
$(function(){
var d2 = new Date();
var d1 = new Date("2014-02-02 23:54:04");
$("a#timedif").html("Diff. Seconds : "+((d2-d1)/1000).toString());
});

If you are okay with that plugin you can modify it a little bit to work with seconds only
var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
seconds < 90 && substitute($l.minute, 1) ||
minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
minutes < 90 && substitute($l.hour, 1) ||
hours < 24 && substitute($l.hours, Math.round(hours)) ||
hours < 42 && substitute($l.day, 1) ||
days < 30 && substitute($l.days, Math.round(days)) ||
days < 45 && substitute($l.month, 1) ||
days < 365 && substitute($l.months, Math.round(days / 30)) ||
years < 1.5 && substitute($l.year, 1) ||
substitute($l.years, Math.round(years));
with this part, go only with converting to seconds
see the fiddle: http://jsfiddle.net/zGXLU/1/

jQuery is just a JavaScript library so JavaScript will just work within your jQuery script:
// specified date:
var oneDate = new Date("November 02, 2017 06:00:00");
// number of milliseconds since midnight Jan 1 1970 till specified date
var oneDateMiliseconds = oneDate.getTime();
// number of milliseconds since midnight Jan 1 1970 till now
var currentMiliseconds = Date.now();
// return time difference in milliseconds
var timePassedInMilliseconds = (currentMiliseconds-oneDateMiliseconds)/1000;
alert(timePassedInMilliseconds);

My working with time difference for calculating each value separately
var start = new Date('Mon Jul 30 2018 19:35:35 GMT+0500');
var end = new Date('Mon Jul 30 2018 21:15:00 GMT+0500');
var hrs = end.getHours() - start.getHours();
var min = end.getMinutes() - start.getMinutes();
var sec = end.getSeconds() - start.getSeconds();
var hour_carry = 0;
var minutes_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hrs = hrs - hour_carry;
if(sec < 0){
sec += 60;
minutes_carry += 1;
}
min = min - minutes_carry;
console.log("hrs",hrs);
console.log("min",min);
console.log("sec",sec);
console.log(hrs + "hrs " + min +"min " + sec + "sec");

Get difference between two timestamps in
Seconds: (get timestamp by new Date().getTime())
diff_in_time = (timestamp_1 - timestamp2);
In Days:
diff_in_days = parseInt((timestamp_1 - timestamp2) / (1000 * 3600 * 24));

Related

Time difference in javascript

var time_1 = '13:44:25:912';
var time_2 = '14:45:30:910';
var inTime=time_1.split(":");
var outTime= time_2.split(":");
var hr = outTime[0] - inTime[0];
var min = ((outTime[1] - inTime[1])+hr*60)%60;
var sec = ((outTime[2] - inTime[2])+min*60)%60;
var milli = ((outTime[3] - inTime[3])+sec*1000)%1000;
document.write(milli);
document.write("<br>"+sec);
document.write("<br>"+min);
document.write("<br>"+hr);
Hey Friends I am need to find time difference in milliseconds I am able to get the difference in HH:MM:SS:Milli now i have convert all into milli plz help for the same
total milliseconds would be milli + (sec * 1000) + (min * 60000) + (hr * 3600000)
You can use the Date.parse function to get the number of milliseconds since January 1, 1970, 00:00:00 UTC. You need to pass a date-part to the string, but it doesn't really matter as long as you keep it the same in both strings.
JavaScript
var time1 = Date.parse("01 Jan 2000 13:44:25:912"),
time2 = Date.parse("01 Jan 2000 14:45:30:910");
console.log(time2 - time1);
Output
3664998
See jsFiddle

Find time difference of 24 hr format

How do I get the time difference of two values of 24hr format?
For example
var time1 = 22:30:00,
time2 = 06:30:00;
Difference should come as 08:00:00
You are much better off to do this type of maths with full date objects, otherwise you have to make guesses about the time values such as if the finish is less that the start, it must be on the next day.
The following includes a couple of helper functions and a main function to get the difference.
// Convert h:m:s to seconds
function hmsToSecs(s) {
var b = s.split(':');
return b[0]*3.6e3 + b[1]*60 + +b[2];
}
// Convert seconds to hh:mm:ss
function secsToHMS(n) {
function z(n){return (n<10? '0':'') + n;}
var sign = n < 0? '-' : '';
n = Math.abs(n);
return sign + z(n/3.6e3|0) + ':' + z(n%3.6e3/60|0) + ':' + z(n%60);
}
// Calculate time difference between two times
// start and finish in hh:mm:ss
// If finish is less than start, assume it's the following day
function timeDiff(start, finish) {
var s = hmsToSecs(start);
var f = hmsToSecs(finish);
// If finish is less than start, assume is next day
// so add 24hr worth of seconds
if (f < s) f += 8.64e4;
return secsToHMS(f - s);
}
console.log(timeDiff('22:30:00','06:30:00')); // 08:00:00
console.log(timeDiff('06:30:00','22:30:00')); // 16:00:00
Using full date objects, you can do:
var start = new Date(2014,5,5,22,30); // 22:30:00 on 5 June 2014
var finish = new Date(2014,5,6,6,30); // 06:30:00 on 6 June 2014
// Subtract dates to get difference in ms, convert to seconds and format
console.log(secsToHMS((finish - start)/1000)); // 08:00:00
console.log(secsToHMS((start - finish)/1000)); // -08:00:00
I Suggest that you should use jquery date.js library and then you can use its Timespan class like below:
var future = Date.parseExact("22:30:00", "hh:mm:ss");
var past = Date.parseExact("06:30:00", "hh:mm:ss");
var span = new TimeSpan(future - now);
and your difference in hours is as below:
span.getHours() + ":" span.getMinutes() + ":" span.getSeconds()
If you want Diff function in C#;
DateTime oldDate= "06/01/2014 12:00:00 AM";
TimeSpan timeDiff = DateTime.Now - oldDate;
int diff =Convert.ToInt32(timeDiff.TotalHours);
if you want it in JavaScript thats a script block should help you;
function diffDateTime(startDT, endDT) {
if (typeof startDT == 'string' && startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)) {
startDT = startDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
startDT = startDT.toString().split(':');
var obstartDT = new Date();
obstartDT.setHours(startDT[0]);
obstartDT.setMinutes(startDT[1]);
obstartDT.setSeconds(startDT[2]);
}
else if (typeof startDT == 'string' && startDT.match(/^now$/i)) var obstartDT = new Date();
else if (typeof startDT == 'string' && startDT.match(/^tomorrow$/i)) {
var obstartDT = new Date();
obstartDT.setHours(24);
obstartDT.setMinutes(0);
obstartDT.setSeconds(1);
}
else var obstartDT = new Date(startDT);
if (typeof endDT == 'string' && endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}[amp ]{0,3}$/i)) {
endDT = endDT.match(/^[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}/);
endDT = endDT.toString().split(':');
var obendDT = new Date();
obendDT.setHours(endDT[0]);
obendDT.setMinutes(endDT[1]);
obendDT.setSeconds(endDT[2]);
}
else if (typeof endDT == 'string' && endDT.match(/^now$/i)) var obendDT = new Date();
else if (typeof endDT == 'string' && endDT.match(/^tomorrow$/i)) {
var obendDT = new Date();
obendDT.setHours(24);
obendDT.setMinutes(0);
obendDT.setSeconds(1);
}
else var obendDT = new Date(endDT);
var secondsDiff = (obendDT.getTime() - obstartDT.getTime()) > 0 ? (obendDT.getTime() - obstartDT.getTime()) / 1000 : (86400000 + obendDT.getTime() - obstartDT.getTime()) / 1000;
secondsDiff = Math.abs(Math.floor(secondsDiff));
var oDiff = {}; // object that will store data returned by this function
oDiff.days = Math.floor(secondsDiff / 86400);
oDiff.totalhours = Math.floor(secondsDiff / 3600); // total number of hours in difference
oDiff.totalmin = Math.floor(secondsDiff / 60); // total number of minutes in difference
oDiff.totalsec = secondsDiff; // total number of seconds in difference
secondsDiff -= oDiff.days * 86400;
oDiff.hours = Math.floor(secondsDiff / 3600); // number of hours after days
secondsDiff -= oDiff.hours * 3600;
oDiff.minutes = Math.floor(secondsDiff / 60); // number of minutes after hours
secondsDiff -= oDiff.minutes * 60;
oDiff.seconds = Math.floor(secondsDiff); // number of seconds after minutes
return oDiff;
}
usage;
var objDiff = diffDateTime('06/01/2014 12:00:00 AM', 'now');
var dtdiff = objDiff.days + ' days, ' + objDiff.hours + ' hours, ' + objDiff.minutes + ' minutes, ' + objDiff.seconds + ' seconds';
Important: You have to remember that DateTime format must be in en-US format dd/MM/yyyy hh:mm:ss.

Javascript countdown timer can't set half past hour

I'm trying to use a countdown timer to count to a certain time everyday (monday to friday). So far everything works, except it can only be set to count to a certain hour (based on the 24 hour clock) without a half hour included. So for example, if I wanted to count to 4PM, I'd set var target = 16; but if I wanted 4:30 and I tried to set var target = 1630; it doesn't work. Unfortunately I don't have much experience with javascript, but I believe the problem is either with the way it's evaluating the target time using the getHours function but not sure where to take it from there.
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown() {
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 5) ) { // Monday to Friday only
var target = 15; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}
var timerRunning = setInterval('countDown()', 1000);
}
If you're ok with considering another method, the following javascript will count down (in seconds) to any date in the future (and count up after the date has passed).
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
var target = new Date(2014, 0, 30, 12, 30, 0, 0)
function countdown(id, targetDate){
var today = new Date()
targetDate.setDate(today.getDate())
targetDate.setFullYear(today.getFullYear())
targetDate.setMonth(today.getMonth())
var diffMillis = targetDate - today
if (diffMillis >= 0){
document.getElementById(id).innerHTML = millisToString(diffMillis)
}
}
setInterval(function(){countdown('seconds', target)},1000)
It uses the javascript date object, so you can literally use any date.
Updated example to do:
format the countdown using hours:minutes:seconds etc
stop the timer after the date is reached
Updated: updated code to override the targetDate to today's date.
Example: http://jsfiddle.net/kKx7h/5/
For 4:30PM, try var target = 16.5 instead of var target = 1630;
You now need to add another variable for the minutes. We can have target as an object literal rather than declare two variables for time:
var target={hour: 15, minute:30};
if ( (now.getHours() < target.hour) && () now.getMinutes() < target.minute ){

javascript adding minutes in a loop

Can't figure this out, from 9:00 to 10:00 everything's correct, but then it all goes haywire. after 10:00 it jumps to 11:15 and then to 12:30
I am simply adding minutes to a date/time to increment an array in 15 minute intervals, is it that I can only add a maximum of 60 minutes ??
function pad(val,max) {
var str = val.toString();
return str.length < max ? pad("0" + str, max) : str;
}
function cboHrs(){
var now = new Date();
now.setHours(9);
var hrs = [];
for (var i=1;i<36;i++){
var hr = {};
now.setMinutes(i*15);
hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
hr.val = hr.txt;
hrs.push(hr);
}
return hrs;
}
console.log(cboHrs());
Anthony got to the actual problem before me...
After the 5th iteration, you are setting the minutes to become 75 (ie,
5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next
value after 10:00 becomes 11:15
- Anthony Forloney
This code should work to set the time correctly.
function cboHrs(){
var now = new Date();
var hrs = [];
for (var i=1;i<36;i++){
var hr = {};
// add another hour every 4th iteration
now.setHours(9 + parseInt(i / 4));
// add 15 minutes every iteration, starting back at 0 on the 4th
now.setMinutes((i % 4) * 15);
hr.txt = pad(now.getHours(),2) +':'+pad(now.getMinutes(),2);
hr.val = hr.txt;
hrs.push(hr);
}
return hrs;
}
The problem lies within the now.setMinutes(i*15); line of code. After the 5th iteration, you are setting the minutes to become 75 (ie, 5 * 15 = 75) which is an 1 hour and 15 minutes which is why the next value after 10:00 becomes 11:15

How to add hours to a Date object?

It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).

Categories

Resources