package datetest2004;

import java.util.Calendar;
import java.util.StringTokenizer;
import javax.swing.*;

//--------------------------------------------------------------------------
// clsDate class stores date in mm, dd, and yyyy variables.
//--------------------------------------------------------------------------
public class clsDate
{
     private int mm;
     private int dd;
     private int yyyy;

     //----------------------------------------------------------------------
     //----------------------------------------------------------------------
     // CONSTRUCTORS AND FINALIZERS
     //----------------------------------------------------------------------
     //----------------------------------------------------------------------

     //----------------------------------------------------------------------
     // No-argument constructor initializes instance variables to current
     // date values.
     //----------------------------------------------------------------------
     public clsDate ( )
     {
          Calendar today = Calendar.getInstance(); // read current date
          int m = today.get(Calendar.MONTH) + 1; // set mm to current month
          int y = today.get(Calendar.YEAR); // set yyyy to current year
          int d = today.get(Calendar.DAY_OF_MONTH); // set dd to current day
     
          setDate (m, d, y);
     }

     //----------------------------------------------------------------------
     // Three-argument constructor initializes instance variables to
     // parameter values.
     //----------------------------------------------------------------------
     public clsDate (int mm, int dd, int yyyy)
     {
          setDate ( mm, dd, yyyy);
     }

     //----------------------------------------------------------------------
     // Calls finalize of superclass.
     //----------------------------------------------------------------------
     public void finalize() throws Throwable
     {
          super.finalize();
     }


     //----------------------------------------------------------------------
     //----------------------------------------------------------------------
     // MUTATOR METHODS
     //----------------------------------------------------------------------
     //----------------------------------------------------------------------

     //---------------------------------------------------------------------------------------------------------------------
     // This mutator method sets the instance variables by validating the parameter values 
     // and then setting the values of the instance variables. 
     //---------------------------------------------------------------------------------------------------------------------
     public void setDate(int mth, int dy, int yr)
     {
          mm = checkMonth(mth);
          yyyy = checkYear(yr);
          dd = checkDay(this.mm, dy, this.yyyy);
     }

     //----------------------------------------------------------------------
     //----------------------------------------------------------------------
     // ACCESSOR METHODS
     //----------------------------------------------------------------------
     //----------------------------------------------------------------------

     //----------------------------------------------------------------------
     // Formats the date using the format specified in the formatSelector:
     // Symbol Meaning Presentation Example
     // -------- ------- ------------ -------
     // y year (Number) 1996
     // M month in year (Text & Number) July & 07
     // d day in month (Number) 10
     //
     // For month, 3 Ms or more, use text, otherwise use number.
     // Year is handled specially; that is, if the count of 'y' is 2 or less,
     // the Year will be truncated to 2 digits.
     //
     // Any characters in the pattern that are not in the ranges of ['a'..'z']
     // and ['A'..'Z'] will be treated as quoted text. For instance, characters
     // like ':', '.', ' ', '#' and '@' will appear in the resulting text
     // even they are not embraced within single quotes. (Not yet.)
     //
     // Format Pattern Result
     // -------------- ------
     // "yyyy.MM.dd" 1996.07.10
     // "MMM d, ''yy" July 10, '96
     // "yyyyy.MMMMM.dd" 1996.July.10
     //
     //----------------------------------------------------------------------
     public String format (String formatSelector)
     {
          String token="";
          String resultString="";
     
          StringTokenizer tokenList = new StringTokenizer( formatSelector, " ,.'/", true );

          while (tokenList.hasMoreTokens())
          {
               token = tokenList.nextToken();
               switch (token.charAt(0)) 
               {
                    case 'M': case 'm':
                         if (this.mm > 0)
                         {
                              if (token.length() >= 3)
                                   resultString += getStrMonth();
                              else
                                   resultString += String.valueOf(this.mm);
                         }
                         break;
                    case 'D': case 'd':
                         if ((this.dd > 0) && (this.mm > 0)) resultString += String.valueOf(this.dd);
                         break;
                    case 'Y': case 'y':
                         String strYear = String.valueOf(this.yyyy);
                         if (token.length() <= 2)
                              resultString += strYear.substring( strYear.length()-2 );
                         else
                              resultString += String.valueOf(this.yyyy);
                         break;
                    case ',':case ' ':
                         if (this.mm > 0)
                         {
                              resultString += String.valueOf(token.charAt(0));
                         }
                         break;
                    default:
                         resultString += String.valueOf(token.charAt(0));
               }
          }
          return resultString;
     }


     //----------------------------------------------------------------------
     //----------------------------------------------------------------------
     // PRIVATE UTILITY METHODS
     //----------------------------------------------------------------------
     //----------------------------------------------------------------------

     //----------------------------------------------------------------------
     // Verifies month value; sets to current month if invalid
     //----------------------------------------------------------------------
     private int checkMonth( int mn)
     {
          // check month
          Calendar today = Calendar.getInstance(); // read current date
          if ( mn > 0 && mn <= 12 ) // validate the month
               return mn;
          else 
          {
               JOptionPane.showMessageDialog(null, "Month " + mn +
                                         " invalid. Reset to current month.", "Error", 
                                         JOptionPane.ERROR_MESSAGE);
               return today.get(Calendar.MONTH) + 1; // return current month
          }
     }

     //----------------------------------------------------------------------
     // Verifies year value; sets to current year if invalid
     //----------------------------------------------------------------------
     private int checkYear (int yr)
     {
          // check year
          Calendar today = Calendar.getInstance(); // read current date
          if (yr >= 1000 && yr <= 32767)
               return yr;
          else 
          {
               JOptionPane.showMessageDialog(null, "Year " + yr +
                                         " invalid. Reset to current year.", "Error", 
                                         JOptionPane.ERROR_MESSAGE);
               return today.get(Calendar.YEAR); // return current year
          }
     }

     //----------------------------------------------------------------------
     // Utility method to confirm proper day value based on month and year.
     // Sets to current month if invalid
     //----------------------------------------------------------------------
     private int checkDay(int month, int testDay, int year)
     {
          Calendar today = Calendar.getInstance(); // read current date
          int daysPerMonth[] = { 31, 31, 28, 31, 30, 31, 30, 31, 31, 30,
                                                                           31, 30, 31 };

          if ( testDay >= 0 && testDay <= daysPerMonth[ month ] )
               return testDay;

          if ( month == 2 &&           // February: Check for leap year
               testDay == 29 && 
               ( year % 400 == 0 ||
               ( year % 4 == 0 && year % 100 != 0 ) ) )
               return testDay;

          JOptionPane.showMessageDialog(null, "Day " + testDay +
                                         " invalid. Reset to current day.", "Error", 
                                         JOptionPane.ERROR_MESSAGE);
          return today.get(Calendar.DAY_OF_MONTH); // return current day
     }

     //----------------------------------------------------------------------
     // Returns the month name.
     //----------------------------------------------------------------------
     private String getStrMonth()
     {
          String monthNames[] = { "", "January", "February", "March", "April",
                         "May", "June", "July", "August",
                         "September", "October", "November", "December" };
          return monthNames[this.mm];
     }

     //----------------------------------------------------------------------
     //----------------------------------------------------------------------
     // Override methods inherited from Object class
     //----------------------------------------------------------------------
     //----------------------------------------------------------------------

     //----------------------------------------------------------------------
     // Returns a string version of the instance variables concatenated in
     // mm/dd/yyyy format. Note: 
     //----------------------------------------------------------------------
     public String toString()
     {
          return mm + "/" + dd + "/" + yyyy;
     }

     //----------------------------------------------------------------------
     // Returns a new clsDate object that is a duplicate of the current object.
     //--------------------------------------------------------------------- 
     public Object clone()
     {
          return new clsDate(this.mm, this.dd, this.yyyy);
     }

     //----------------------------------------------------------------------
     // Determines whether its parameter is a clsDate object with attributes
     // that are equivalent to the invoking clsDate object.
     //--------------------------------------------------------------------- 
     public boolean equals (Object compObj)
     {
          if (compObj instanceof clsDate)
          {
               clsDate comp = (clsDate) compObj;
               int mComp = Integer.parseInt(comp.getMonth());
               int dComp = Integer.parseInt(comp.getDay());
               int yComp = Integer.parseInt(comp.getYear());
               return (Integer.parseInt(getMonth())==mComp) &&
                         (Integer.parseInt(getDay())==dComp) &&
                         (Integer.parseInt(getYear())==yComp); 
          }
          else
          {
               return false;
          }
     }
}

 

clsDate date1 = new clsDate();
System.out.println(date1.format("MMM d, yyyy"));
date1.setDay(30);
System.out.println(date1.format("MMM d, yyyy"));
date1.setMonth(3);
date1.setDay(30);
System.out.println(date1.format("MMM d, yyyy"));
date1.setMonth(2);
System.out.println(date1.format("MMM d, yyyy"));
System.out.println(date1.toString());

 

int month = jtfMonth.getText().equals("") ? 0 :(Integer.valueOf(jtfMonth.getText().trim())).intValue();
int day = jtfDay.getText().equals("") ? 0 : (Integer.valueOf(jtfDay.getText().trim())).intValue();
int year = jtfYear.getText().equals("") ? 0 : (Integer.valueOf(jtfYear.getText().trim())).intValue();

clsDate testDate = new clsDate(month, day, year);

// Display result
if ((Integer.parseInt(testDate.getMonth()) == 0) && (Integer.parseInt(testDate.getDay()) == 0))
{
     jtfDate.setText(testDate.format("yyyy"));
}
else if (Integer.parseInt(testDate.getDay()) == 0)
{
     jtfDate.setText(testDate.format("MMM, yyyy"));
}
else jtfDate.setText(testDate.format("MMM d, yyyy"));