Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
package open.source;
import java.io.Serializable;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Visit http://monisiqbal.blogspot.com
* Follow me on: http://www.twitter.com/monisiqbal
* @author monis.iqbal
*
*/
public class TimeZoneDSTUtil {
/**
* DST details for the time zone i.e. when DST is applied and when it ends.
* @return
*/
public static String getDSTDetails(TimeZone timeZone) {
if (timeZone.getDSTSavings() > 0) {
/* Java's TimeZone related classes compute the start and end date of DST application but
* do not expose it. The only way is to decipher the toString method which fortunately
* prints enough information for us to deduce our required data.
*/
Pattern pattern = Pattern.compile("startMonth=(\\d+),startDay=(\\d+),.+endMonth=(\\d+),endDay=(\\d+),");
Matcher m = pattern.matcher(timeZone.toString());
if (m.find()) {
Calendar startCal = Calendar.getInstance();
Calendar endCal = Calendar.getInstance();
startCal.set(Calendar.MONTH, Integer.valueOf(m.group(1)));
startCal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(m.group(2)));
endCal.set(Calendar.MONTH, Integer.valueOf(m.group(3)));
endCal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(m.group(4)));
final SimpleDateFormat monthFormatter = new SimpleDateFormat("MMMM");
return new MessageFormat("Daylight savings starts at day {0} of {1}, ends at day {2} of {3}")
.format(new Serializable[] {
startCal.get(Calendar.DAY_OF_MONTH), monthFormatter.format(startCal.getTime()),
endCal.get(Calendar.DAY_OF_MONTH), monthFormatter.format(endCal.getTime())
}
);
}
}
return "NA";
}
/**
* Prints out all available TimeZones in the JVM
*
*/
public static void printAllTimeZoneDSTs() {
String[] availableIds = TimeZone.getAvailableIDs();
for (String timeZoneId : availableIds) {
printTimeZoneDST(timeZoneId);
}
}
public static void printTimeZoneDST(String timeZoneId) {
TimeZone tz = TimeZone.getTimeZone(timeZoneId);
System.out.println(tz.getID() + ", DST: " + getDSTDetails(tz));
}
public static void main(String[] args) {
//printAllTimeZoneDSTs();
printTimeZoneDST("US/Pacific");
printTimeZoneDST("US/Mountain");
printTimeZoneDST("Brazil/East");
printTimeZoneDST("Asia/Karachi");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment