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