Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
<pre lang="text"><pre lang="text"><pre lang="text">
Hi All, little help needed on how we sort timezone based on the offset value. To put it simple, I got a array like below


you can check the code here. http://jsfiddle.net/arunrajkhumar/2nvwzr6o/[^]


The output looks like this,
(GMT-2:0) Atlantic/South_Georgia
(GMT-11:0) Pacific/Midway
(GMT-10:0) Pacific/Rarotonga
(GMT+3:0) Africa/Asmara
(GMT+2:0) Africa/Bujumbura
(GMT+5:45) Asia/Kathmandu
(GMT+14:0) Pacific/Kiritimati
(GMT+12:45) Pacific/Chatham
(GMT+12:0) Pacific/Wallis
(GMT+11:30) Pacific/Norfolk
(GMT+12:45) Pacific/Chatham

But the problem is, it needs to be sorted in order like -12, -11, -10, .. 0... 1,2,3 .. +12.. we can windows os timezone dropdown in this order.

How can we achieve this ? Please share your thoughts.
Posted
Updated 16-Jul-15 1:15am
v2

Your timezone data doesn't contain the offset value, so you'll need to extract it from the label.

Something like this should work:
JavaScript
timeZone.sort( function( a, b ) {
    var re = /^\(GMT([+-]\d{1,2}):(\d{1,2})\).*$/;
    var aOffset = parseFloat(a.label.replace(re, "$1.$2"));
    var bOffset = parseFloat(b.label.replace(re, "$1.$2"));
    return aOffset < bOffset ? -1 : aOffset > bOffset ? 1 : 0;
});


https://jsfiddle.net/2nvwzr6o/1/[^]

EDIT: Updated to properly parse the offset when it's not a whole number of hours.
 
Share this answer
 
v2
Wow !! Quite Stunning Richard. :) :) Thanks a lot.

But when timezone starts with same offset like this

(GMT+12:50) Pacific/Chatham
(GMT+12:45) Pacific/Chatham

it should be sorted like this

(GMT+12:45) Pacific/Chatham
(GMT+12:50) Pacific/Chatham


Apart from this, I have no complaints thanks :)
 
Share this answer
 
Comments
Richard Deeming 17-Jul-15 7:30am    
Don't post comments as new solutions; use the "Have a Question or Comment?" button under the relevant solution. That way, the user who posted the solution will be notified of your comment.

I've updated my solution with the fix.
zingcoders 19-Jul-15 2:12am    
Thanks for info, Richard. but whats that $1. $2 ?
zingcoders 19-Jul-15 2:12am    
Thanks for info, Richard. but whats that $1. $2 ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900