Last active
November 2, 2019 12:19
-
-
Save lpellegr/9dd1bf4436a45b090cc6a7b374b99b4c to your computer and use it in GitHub Desktop.
TimeZone List Generator from Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Comparator; | |
import java.util.List; | |
import java.util.TimeZone; | |
import java.util.concurrent.TimeUnit; | |
public class TimeZoneList { | |
public static void main(String[] args) { | |
String[] zoneIds = TimeZone.getAvailableIDs(); | |
List<TimeZoneEntry> entries = new ArrayList<>(zoneIds.length); | |
for (String id : zoneIds) { | |
entries.add(generateEntry(TimeZone.getTimeZone(id))); | |
} | |
entries.sort(Comparator.comparingInt(a -> a.offset)); | |
entries.forEach(e -> System.out.println(e.toJavaScript())); | |
} | |
private static TimeZoneEntry generateEntry(TimeZone tz) { | |
long hours = TimeUnit.MILLISECONDS.toHours(tz.getRawOffset()); | |
long minutes = TimeUnit.MILLISECONDS.toMinutes(tz.getRawOffset()) - TimeUnit.HOURS.toMinutes(hours); | |
minutes = Math.abs(minutes); | |
String result = String.format(hours >= 0 ? "+%d:%02d" : "%d:%02d", hours, minutes, tz.getID()); | |
return new TimeZoneEntry(tz.getRawOffset(), tz.getID(), result); | |
} | |
} | |
class TimeZoneEntry { | |
int offset; | |
String id; | |
String label; | |
TimeZoneEntry(int offset, String id, String label) { | |
this.offset = offset; | |
this.id = id; | |
this.label = label; | |
} | |
@Override | |
public String toString() { | |
return label; | |
} | |
public String toJavaScript() { | |
StringBuilder result = new StringBuilder(); | |
result.append('{'); | |
result.append("rawOffset: "); | |
result.append(offset); | |
result.append(", offset:\""); | |
result.append(label); | |
result.append("\", id:\""); | |
result.append(id); | |
result.append("\"},"); | |
return result.toString(); | |
} | |
} |
Author
lpellegr
commented
Nov 2, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment