Does anyone know how to calculate the difference between two datetimes in Javascript ?
For example: 2018-01-17T21:18:00
and 2018-01-16T21:17:00
I tried to split them and add them together afterwards but I noticed the hours are already calculated in the date difference.
Why don´t people understand the simple difference between date and datetime ? Stop Voting down, or writing stuipid ments.
Does anyone know how to calculate the difference between two datetimes in Javascript ?
For example: 2018-01-17T21:18:00
and 2018-01-16T21:17:00
I tried to split them and add them together afterwards but I noticed the hours are already calculated in the date difference.
Why don´t people understand the simple difference between date and datetime ? Stop Voting down, or writing stuipid ments.
Share Improve this question edited Jan 20, 2018 at 20:06 Deadpool asked Jan 20, 2018 at 18:58 DeadpoolDeadpool 2043 silver badges14 bronze badges 5- 1 Possible duplicate of Get difference between 2 dates in JavaScript? – Nikola Andreev Commented Jan 20, 2018 at 19:04
- 3 @NikolaAndreev Date and DateTime - BIG difference – Deadpool Commented Jan 20, 2018 at 19:05
- 1 @Deadpool in which form do you want the result? The as datetime? – Orkhan Alikhanov Commented Jan 20, 2018 at 19:12
- The best would be like 1 Day, 1 Hour and 1 Minute, but I can format it myself afterwards. :) – Deadpool Commented Jan 20, 2018 at 19:14
- If you use Moment.js library it has lot of functions to do that already see stackoverflow./questions/25150570/… – Aman B Commented Jan 20, 2018 at 19:22
2 Answers
Reset to default 3use Math.abs
if you would get a negative value (ie if you don't know if a
is lower then b
)
Date object is essentially a number and you can do mathematical operations with it without getting timestamp
var a = new Date('2018-01-17T21:18:00')
var b = new Date('2018-01-16T21:17:00')
console.log(a - b) // possible use
console.log(Math.abs(a - b)) // safe to use
console.log(Math.abs(b - a)) // safe to use
console.log(b - a) // not what you want
from there you just calculate how many days/hours/min there is
you can use valueOf -> https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf
let date1 = new Date('2018-01-17T21:18:00')
let date2 = new Date('2018-01-16T21:17:00')
//you get the difference in ms
let difference = Math.abs(date1.valueOf()-date2.valueOf())
//you can then convert to any format
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745351073a4623834.html
评论列表(0条)