/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. //=== Dates.java ======== 

2. import java.applet.Applet

3. import java.awt.*; 

4. import java.awt.event.*; 

5. import java.text.*; 

6. import java.util.*; 

7.  

8. public class Dates extends Applet 

9.     implements ActionListener 

10.

11.   SimpleDateFormat sdf = new SimpleDateFormat( "yyyy/MM/dd" ) ; 

12.    

13.   TextField tft  = new TextField() ; 

14.   TextField tf= new TextField( "2007/07/27" ) ; 

15.   TextField tfres  = new TextField( 20 ) ; 

16.   Button btn = new Button( "Do it" ) ; 

17.    

18.   public void 

19.   actionPerformed( ActionEvent ev ) 

20.   { 

21.       String sd = sdf.format( new Date() ); 

22.       tft.setText( sd ); 

23.       String tx = tf.getText() ; 

24.       sdf.setLenient( false ) ; 

25.       try

26.        Date dtent = sdf.parse( tx ) ; 

27.        doit( dtent  ); 

28.       } 

29.       catch ( ParseException e ) 

30.       { tfres.setText( "Date entered not accepted" ) ; } 

31.       tf.requestFocus (); 

32.   } 

33.   private void doit( Date d ) 

34.   { 

35.     GregorianCalendar today = new GregorianCalendar(); 

36.     clearTime( today ); 

37.      

38.     GregorianCalendar dtentered = new GregorianCalendar(); 

39.     dtentered.setTime( d ); 

40.     clearTime( dtentered ); 

41.    

42.     GregorianCalendar dtcalc = null

43.     int days = 0

44.     if ( dtentered.after(today) ) 

45.     { 

46.       dtcalc = (GregorianCalendar) today.clone(); 

47.        

48.       while ( dtcalc.before( dtentered ) ) 

49.       { 

50.          dtcalc.add( Calendar.DATE, 1 ); 

51.          days++; 

52.       } 

53.       tfres.setText("Period in days : " + days );   

54.     } 

55.     else 

56.       tfres.setText("Must be future date" ); 

57.      

58.     tf.requestFocus(); 

59.     tf.setCaretPosition( tf.getText().length() ); 

60.   } 

61.   private void clearTime( Calendar cal ) 

62.   { 

63.     cal.clear(Calendar.HOUR_OF_DAY); 

64.     cal.clear(Calendar.AM_PM); 

65.     cal.clear(Calendar.HOUR); 

66.     cal.clear(Calendar.MINUTE); 

67.     cal.clear(Calendar.SECOND); 

68.     cal.clear(Calendar.MILLISECOND); 

69.   } 

70.   public void init () 

71.   { 

72.       String sd = sdf.format( new Date() ); 

73.       tft.setText( sd ); 

74.       tft.setEditable( false ) ; tfres.setEditable( false ) ; 

75.       add( tft ) ; add( tf ) ; add( tfres ) ; add( btn ) ; 

76.       tf.addActionListener( this ) ; 

77.       btn.addActionListener( this ) ; 

78.       setBackground( Color.CYAN ) ; 

79.       tf.requestFocus(); 

80.       tf.setCaretPosition( tf.getText().length() ); 

81.       setFont( new Font("SansSerif",Font.BOLD,14 ) ); 

82.   } 

83.

84. // GregorianCalendar gc = 

85. //   new GregorianCalendar( 2006, 2,18, 16,15,00 ); 

86.