How do I calculate how many seconds between two dates?
I'm taking YYYY & ZZZZ to mean integer values which mean the year, MM & NN to mean integer values meaning the month of the year and DD & EE as integer values meaning the day of the month.
var t1 = new Date(YYYY, MM, DD, 0, 0, 0, 0);
var t2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
A handy source for future reference is the MDN siteAlternatively, if your dates come in a format javascript can parse
var dif = Date.parse(MM + " " + DD + ", " + YYYY) - Date.parse(NN + " " + EE + ", " + ZZZZ);
and then you can use that value as the difference in milliseconds (dif in both my examples has the same meaning) How to calculate the amount of elapsed seconds between two ISO timestamps?
You can use moment#diff
:
const diff = (start, end) =>
moment(end).diff(moment(start), 'seconds');
console.log( diff('2021-03-09T22:47:54.392Z', new Date().toISOString()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
Get time difference between two dates in seconds
The Code
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000
as pointed out in the comments unless you're using typescript.The explanation
You need to call thegetTime()
method for the Date
objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate()
method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime()
method, representing the number of milliseconds since January 1st 1970, 00:00Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.For example in Luxon we would do t1.diff(t2, "seconds")
which is beautiful.
Useful docs for this answer
- Why 1970?
- Date object
- Date's getTime method
- Date's getDate method
- Need more accuracy than just seconds?
How to get the number of seconds between two dates in javascript?
It's a matter of operations order, you're dividing the countDownDate
by 1000
before doing the subtraction (you're calculating now - countDownDate / 1000
however, you should calculate (now - countDownDate) / 1000
, subtraction first):
var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();var dist = 347155200;// Update the count down every 1 secondvar x = setInterval(function() {
// Get todays date and time var now = new Date("Mar 16, 2019 16:33:30");
// Find the distance between now and the count down date var distance = Math.abs((now - countDownDate) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = distance;
// If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; }}, 1000);
<p id="demo"></p>
JavaScript calculate difference in seconds between to datetime
Try to convert recordDate to a Date Object first
var match = recordDate.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/);
var date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);
var currentDate = new Date();
var differenceInSeconds = Math.abs(date.getTime() - currentDate.getTime())/1000;
DEMOvar recordDate = '2016-04-20 17:52:33';var match = recordDate.match(/^(\d+)-(\d+)-(\d+) (\d+)\:(\d+)\:(\d+)$/);var date = new Date(match[1], match[2] - 1, match[3], match[4], match[5], match[6]);alert(date.toString());var currentDate = new Date();
var differenceInSeconds = Math.abs(date.getTime() - currentDate.getTime())/1000;alert(differenceInSeconds);
Time difference in seconds between given two dates
Assuming GNU implementation based OS, you can use date
's option %s
and -d
to calculate the time difference in seconds
using command substitution and arithmetic operations.
START="2019-01-05 23:52:00"
END="2019-01-06 00:02:10"
Time_diff_in_secs=$(($(date -d "$END" +%s) - $(date -d "$START" +%s)))
echo $Time_diff_in_secs
Output:610
Hope this helps!!! Javascript - time difference in seconds between two dates
If you want to compare a date to today, there is no need to pass today as a variable to the function (the code will get a little bit simple).
function getTimeDiff(year, month, day) {
var today = new Date();
var targetDate = new Date(year, month, day);
return Math.round( (targetDate.getTime() - today.getTime()) / 1000);
}
console.log(getTimeDiff(2019,6,6));
Because getTime outputs the value in miliseconds, I have divided by 1000 and rounded the value, so you get an integer.The code outputs somethink like 2293103
(tested in Chrome and Firefox)
Difference between two time.Time objects
You may use Time.Sub()
to get the difference between the 2 time.Time
values, result will be a value of time.Duration
.
When printed, a time.Duration
formats itself "intelligently":
t1 := time.Now()
t2 := t1.Add(time.Second * 341)
fmt.Println(t1)
fmt.Println(t2)
diff := t2.Sub(t1)
fmt.Println(diff)
Output:2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:05:41 +0000 UTC
5m41s
If you want the time format HH:mm:ss
, you may constuct a time.Time
value and use its Time.Format()
method like this:out := time.Time{}.Add(diff)
fmt.Println(out.Format("15:04:05"))
Output:00:05:41
Try the examples on the Go Playground.Of course this will only work if the time difference is less than a day. If the difference may be bigger, then it's another story. The result must include days, months and years. Complexity increases significnatly. See this question for details:
golang time.Since() with months and years
The solution presented there solves this issue by showing a function with signature:
func diff(a, b time.Time) (year, month, day, hour, min, sec int)
You may use that even if your times are within 24 hours (in which case year
, month
and day
will be 0
). How do I check the difference, in seconds, between two dates?
if you want to compute differences between two known dates, use total_seconds
like this:
import datetime as dt
a = dt.datetime(2013,12,30,23,59,59)
b = dt.datetime(2013,12,31,23,59,59)
(b-a).total_seconds()
86400.0#note that seconds doesn't give you what you want:
(b-a).seconds
0
Related Topics
Removing Duplicate Objects with Underscore for JavaScript
Typeerror: $ Is Not a Function Wordpress
Unexpected Token Illegal in Webkit
Angular Ui-Router $Urlrouterprovider .When Not Working When I Click <A Ui-Sref="...">
What's Wrong with Var X = New Array();
Razor MVC Populating JavaScript Array with Model Array
JavaScript Loop Variable Scope
Nodejs Timeout a Promise If Failed to Complete in Time
React 18, Useeffect Is Getting Called Two Times on Mount
I Can't Reference an Image in Next.Js
Why Is Window (And Unsafewindow) Not the Same from a Userscript as from a <Script> Tag
How Does Appcelerator Titanium Mobile Work
How to Check If an Embedded Svg Document Is Loaded in an HTML Page
Convert Unix Timestamp to Date Time (Javascript)
Adding Code to a JavaScript Function Programmatically
Authorization of Google Drive Using JavaScript
JavaScript - Generating All Combinations of Elements in a Single Array (In Pairs)