Reputation: 7388
In my React Native app, I'm calculating the difference between a given time and the current time using moment JS
. My code to calculate minsLeft
, the difference between the two times, is:
let minsLeft = moment.duration(moment(request.AcceptedDate, "DD-MMM-YYYY h:mm:ss A")
.subtract(new Date().getTimezoneOffset(), 'minutes')
.add(request.ETA, 'minutes')
.diff(moment())
)
request.AcceptedDate
was 3-May-2020 04:37:31 PM
, and on that day (May 3) at 5pm I was getting a result of 23 minutes, as expected. On some devices though, I was getting values of negative several thousand minutes. The numbers were consistent with the app calculating the current date as 05/03/2021
instead of 03/05/2021
, as if the moment()
function returns something different on different devices.
Has anyone run into anything like this and know where this discrepancy might be coming from?
Upvotes: 0
Views: 1437
Reputation: 433
The issue is with timezones and formatting.
Considering your request to be:
let request = {AcceptedDate: '06-May-2021 11:03:28 AM', ETA:60}
As per your comment AcceptedDate is of the format DD-MMM-YYYY h:mm:ss A
and is already in UTC time.
Here are 2 different approaches to solve your issue:
Approach 1: Using new Date().getTimezoneOffset()
let minsLeft = Math.abs(moment(request_TimeStamp.AcceptedDate).subtract(new Date().getTimezoneOffset(), 'minutes').add(request_TimeStamp.ETA, 'minutes').diff(moment(), 'minutes'))
Approach 2: Using moment().local()
let minsLeft = Math.abs(moment(request_TimeStamp.AcceptedDate).utc(request_TimeStamp.AcceptedDate).local().add(request_TimeStamp.ETA, 'minutes').diff(moment(), 'minutes'))
I have created a Snack with both the above approaches
Kindly Vote and Flag my solution if it helped you in any way. Cheers!
Upvotes: 1
Reputation: 246
var now = "04/05/2021 11:00:00"; //new Date();
var then = "03/05/2021 11:20:00";
var s = moment.utc(moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss");
console.log("s:", s);
//output: 23:40:00
Get difference between two times using moment. Hope it is works for react native. i tried it in react.
Upvotes: 1
Reputation: 105
I also had the same problem. Turns out the moment() function depends on the timezone, date, and time set on the device. As you change your time or date or timezone, you get different results.
Upvotes: 1