BAEL-1317: Adding Java7 examples
This commit is contained in:
parent
232d2d8e81
commit
dbee97c1c1
|
@ -0,0 +1,43 @@
|
|||
package com.baeldung.timezonedisplay;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.TimeZone;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
public class TimezoneDisplayJava7 {
|
||||
|
||||
public List<String> compileListFor(TimezoneDisplayJava7.OffsetBase base) {
|
||||
String[] availableZoneIds = TimeZone.getAvailableIDs();
|
||||
List<String> result = new ArrayList<>(availableZoneIds.length);
|
||||
|
||||
for (String zoneId : availableZoneIds) {
|
||||
TimeZone curTimeZone = TimeZone.getTimeZone(zoneId);
|
||||
|
||||
String offset = calculateOffset(curTimeZone.getRawOffset());
|
||||
|
||||
result.add(String.format("(%s%s) %s", base, offset, zoneId));
|
||||
}
|
||||
|
||||
Collections.sort(result);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private String calculateOffset(int rawOffset) {
|
||||
if (rawOffset == 0) {
|
||||
return "+00:00";
|
||||
}
|
||||
long hours = TimeUnit.MILLISECONDS.toHours(rawOffset);
|
||||
long minutes = TimeUnit.MILLISECONDS.toMinutes(rawOffset);
|
||||
minutes = Math.abs(minutes - TimeUnit.HOURS.toMinutes(hours));
|
||||
|
||||
return String.format("%+03d:%02d", hours, Math.abs(minutes));
|
||||
}
|
||||
|
||||
public enum OffsetBase {
|
||||
GMT, UTC
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
package com.baeldung.timezonedisplay;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class TimezoneDisplayJava7App {
|
||||
|
||||
public static void main(String... args) {
|
||||
TimezoneDisplayJava7 display = new TimezoneDisplayJava7();
|
||||
|
||||
System.out.println("Time zones in UTC:");
|
||||
List<String> utc = display.compileListFor(TimezoneDisplayJava7.OffsetBase.UTC);
|
||||
for (String timeZone : utc) {
|
||||
System.out.println(timeZone);
|
||||
}
|
||||
|
||||
System.out.println("Time zones in GMT:");
|
||||
List<String> gmt = display.compileListFor(TimezoneDisplayJava7.OffsetBase.GMT);
|
||||
for (String timeZone : gmt) {
|
||||
System.out.println(timeZone);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue