/* The applet "Moscow Time" illustrates, how to use the classes Date, GregorianCalendar, TimeZone, and DateFormat. */ import java.applet.Applet; import java.awt.*; import java.util.Date; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.TimeZone; import java.text.DateFormat; public class MoscowTime extends Applet implements Runnable { Font f = new Font("Helvetica", Font.PLAIN, 14); Thread t; TimeZone tz; DateFormat df; // Clock geometry final int clock_w = 50; final int clock_h = 50; final int clock_dx = 5; final int clock_dy = 5; public void init() { // Unfortunately, there is no time zone for Moscow supported // in JDK. So we have to construct the Moscow time zone ("MSD") // from Central Europian Time zone ("ECT"). The Moscow time zone // has the offset +2 hours relatively to CET and the same daylight // savings time, at least for the current and, I hope, future dates. tz = TimeZone.getTimeZone("ECT"); tz.setID("MSD"); tz.setRawOffset(3*60*60*1000); // Offset +3 hours df = DateFormat.getDateTimeInstance( DateFormat.FULL, DateFormat.MEDIUM ); df.setTimeZone(tz); } public void start() { t = new Thread(this, "Date"); t.start(); } public void stop() { t = null; } public void paint(Graphics g) { g.setFont(f); Date d = new Date(); g.setColor(Color.black); g.drawString( df.format(d), clock_dx*3 + clock_w , clock_dy*2 + clock_h / 2 ); drawClock(g); } public void run() { while (t != null) { repaint(); try { Thread.sleep(1000); } catch (Exception e) { System.out.println(e); } } } void drawClock(Graphics g) { g.setColor(Color.blue); g.drawOval(clock_dx, clock_dy, clock_w, clock_h); int cx = clock_dx + clock_w / 2; int cy = clock_dy + clock_h / 2; int dx = (clock_dx * 3) / 4; int dy = (clock_dy * 3) / 4; g.drawLine(cx, clock_dy, cx, clock_dy + dy); g.drawLine(cx, clock_dy + clock_h, cx, clock_dy + clock_h - dy); g.drawLine(clock_dx, cy, clock_dx + dx, cy); g.drawLine(clock_dx + clock_w, cy, clock_dx + clock_w - dx, cy); GregorianCalendar c = new GregorianCalendar(tz); double h = (double) c.get(Calendar.HOUR); // 0..12 double m = (double) c.get(Calendar.MINUTE); // 0..59 double s = (double) c.get(Calendar.SECOND); // 0..59 // Hours double len = 0.5 / 2.; g.setColor(Color.black); double angle = Math.PI / 2. - ((h + m / 60.) * Math.PI / 6); int x = (int)(cx + len * clock_w * Math.cos(angle)); int y = (int)(cy - len * clock_h * Math.sin(angle)); g.drawLine(cx, cy, x, y); // Minutes len = 0.75 / 2.; g.setColor(Color.black); angle = Math.PI / 2. - ((m + s / 60.) * Math.PI / 30); x = (int)(cx + len * clock_w * Math.cos(angle)); y = (int)(cy - len * clock_h * Math.sin(angle)); g.drawLine(cx, cy, x, y); // Seconds len = 0.85 / 2.; g.setColor(Color.red); angle = Math.PI / 2. - (s * Math.PI / 30); x = (int)(cx + len * clock_w * Math.cos(angle)); y = (int)(cy - len * clock_h * Math.sin(angle)); g.drawLine(cx, cy, x, y); } }