The basics of Time and Date

Some definitions:

Java Objects:

Pattern letter
Time component
Example output:
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800

Examples:

Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700


When to use what objects:

      java.util.Date d = new java.util.Date();
     SimpleDateFormat frm = new SimpleDateFormat("MM/dd/yyyy G hh:mm:ss aa z");
     outputField.setText(frm.format(d));
 GregorianCalendar cal = new GregorianCalendar(2004,2,24,12,30,3);  //  create a calendar date Feb 24, 2004 at 12:30:03
 GregorianCalendar checkoutdate = new GregorianCalendar();  // set the date checked out to today's date and time
 GregorianCalendar duedate = new GregorianCalendar();  // set due date to today's date
 duedate.add(GregorianCalendar.DAY_OF_YEAR,14);  //  add 14 days to due date
 Date due = duedate.getTime();  // due date in Date format
      INSERT INTO Orders (id, trans_date, amount)  values (1234, GetDate(), 200.42)




Example:  Retrieve a date field from the result set and enter the date onto JTextFields (month, day, year)

     try{
        PreparedStatement prep = con.prepareStatement("SELECT * FROM orders WHERE ordernumber = ?");
        prep.setInt(1, number);
        ResultSet rs = prep.executeQuery();
        if(rs.next())  // was at least one record found?
        {
         // get record data from result set into local variables
         number = rs.getInt(1);
         String phone = rs.getString(2);
         String product = rs.getString(3);
         short quantity = rs.getShort(4);
         double price = rs.getDouble(5);
         java.sql.Timestamp orderdate = rs.getTimestamp(6);
         // now use SimpleDateFormat to format the time/date, or just use the toString for orderdate
       
        
        }
        else
          messageLabel.setText(number+" not found in Orders table");     
        prep.close();
       }
       catch(SQLException sqle)
       {
        messageLabel.setText("Error during lookup : "+sqle.getMessage());       
       }