01: package bigjava;
02: 
03: import java.text.DateFormat;
04: import java.util.Date;
05: import java.util.TimeZone;
06: 
07: /**
08:    This bean formats the local time of day for a given date
09:    and city.
10: */
11: public class TimeZoneBean
12: {
13:    /**
14:       Initializes the formatter.
15:    */
16:    public TimeZoneBean()
17:    {
18:       timeFormatter = DateFormat.getTimeInstance();
19:    }
20: 
21:    /**
22:       Setter for city property.
23:       @param aCity the city for which to report the local time
24:    */
25:    public void setCity(String aCity)
26:    {      
27:       city = aCity;
28:       zone = getTimeZone(city);
29:    }
30:    
31:    /**
32:       Getter for city property.
33:       @return the city for which to report the local time
34:    */
35:    public String getCity()
36:    {
37:       return city;
38:    }
39: 
40:    /**
41:       Read-only time property.
42:       @return the formatted time
43:    */
44:    public String getTime()
45:    {
46:       if (zone == null) return "not available";
47:       timeFormatter.setTimeZone(zone);
48:       Date time = new Date();
49:       String timeString = timeFormatter.format(time);
50:       return timeString;
51:    }
52: 
53:    /**
54:       Looks up the time zone for a city
55:       @param aCity the city for which to find the time zone
56:       @return the time zone or null if no match is found
57:    */
58:    private static TimeZone getTimeZone(String city)
59:    {
60:       String[] ids = TimeZone.getAvailableIDs();
61:       for (int i = 0; i < ids.length; i++)
62:          if (timeZoneIDmatch(ids[i], city))
63:             return TimeZone.getTimeZone(ids[i]);
64:       return null;
65:    }
66: 
67:    /**
68:       Checks whether a time zone ID matches a city
69:       @param id the time zone ID (e.g. "America/Los_Angeles")
70:       @param aCity the city to match (e.g. "Los Angeles")
71:       @return true if the ID and city match
72:    */
73:    private static boolean timeZoneIDmatch(String id, String city)
74:    {
75:       String idCity = id.substring(id.indexOf('/') + 1);
76:       return idCity.replace('_', ' ').equals(city);
77:    }
78: 
79:    private DateFormat timeFormatter;
80:    private String city;
81:    private TimeZone zone;
82: }