Re: Sorting TimeZone
Wojtek wrote:
How would you sort timezones?
I am trying to sort them according to their offset from UTC. I cannot
use a TreeMap because there are many timezones with the same offset,
which of course over-writes the previously put timezone.
The preferred sort would be offset, then display name.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sorttimezone;
import java.util.Arrays;
import java.util.Comparator;
import java.util.TimeZone;
/**
*
* @author Brenden
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
String [] zonesIDs = TimeZone.getAvailableIDs();
TimeZone [] allTZ = new TimeZone[zonesIDs.length];
for( int i=0; i< allTZ.length; i++ ) {
allTZ[i]=TimeZone.getTimeZone( zonesIDs[i] );
}
Arrays.sort( allTZ, new SortByOffsetAndName() );
for( TimeZone zone : allTZ ) {
System.out.println( zone.getDisplayName() + ": "+
zone.getRawOffset()/1000/60/60 );
}
}
}
class SortByOffsetAndName implements Comparator<TimeZone> {
public int compare( TimeZone o1, TimeZone o2 )
{
if( o1.getRawOffset() != o2.getRawOffset() ) {
return o1.getRawOffset() - o2.getRawOffset();
}
return o1.getDisplayName().compareTo( o2.getDisplayName() );
}
}