I need to sort an array in react native without affecting the timestamp. I'm getting details from the backend with timestamp and I want to sort it. I have done the sorting part with first come first basis using the following code.
const members = out.game.gameMembers.map((elem) => {
return {
id: elem.userId._id,
profileImage: elem.userId.profileImage,
name: elem.userId.name,
status: elem.status,
position: elem.userId.position,
isDeleted: elem.userId.isDeleted,
createdAt: elem.createdAt,
updatedAt:elem.updatedAt
};
});
let sortedMembers = members.sort(function (x, y) {
// return x.updatedAt - y.updatedAt;
return new Date(x.updatedAt) - new Date(y.updatedAt);
});
Here I'm getting the sorted members and sorting it with respect to their timestamp. But the problem is the time zone. If a user 'A' is from Dubai and another user 'B' is from India, the time difference is around two and half hours.
For example user from India updated their profile status at 11:30 AM and after 10 minutes user from Dubai updated his status where the time is 10:00 AM. So at time of sorting then User from Dubai comes first which can't be happen. How exactly solve this issue and sort the details using timestamp first come first in basis. Additionally I'm getting timezone of both Dubai user and Indian user. Thank you
CodePudding user response:
Always store UTC
dates in database and convert them to local dates while using in the App that way you'll have more access to customization
ISO
format is best to store in a database
Example of ISO format: '2022-12-15T06:22:10.299Z'
How to get date in ISO format?
new Date().toISOString()
then to sort them
ISO8601See General principles was designed for lexicographical sort. As such the ISO8601 string representation can be sorted like any other string, and this will give the expected order.
'2007-01-17T08:00:00Z' < '2008-01-17T08:00:00Z' === true
So you would implement:
var myArray = [
{ name:'oldest', date:'2007-01-17T08:00:00Z' },
{ name:'newest', date:'2011-01-28T08:00:00Z' },
{ name:'old', date:'2009-11-25T08:00:00Z' }
];
myArray.sort(function(a, b) {
return (a.date < b.date) ? -1 : ((a.date > b.date) ? 1 : 0);
});
CodePudding user response:
Converting to UTC timezone should work:
const date = new Date()
// Date in the local time zone
console.log(date.toString())
// Date in UTC time zone
console.log(date.toUTCString())