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
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);
        
         GregorianCalendar cal = new GregorianCalendar();
         cal.setTime(orderdate);
         //
         // display data onto screen
         //
         orderNumberField.setText(""+number);
         orderPhoneField.setText(phone);
         orderProductField.setSelectedItem(product);
         orderQuantityField.setText(""+quantity);
         orderPriceField.setText(""+price);
         orderMonthField.setText(""+(cal.get(GregorianCalendar.MONTH)+1));  // add one to make month 1 relative
         orderYearField.setText(""+cal.get(GregorianCalendar.YEAR));
         orderDayField.setText(""+cal.get(GregorianCalendar.DAY_OF_MONTH));
         messageLabel.setText("");  // clear out message label
        }
        else
          messageLabel.setText(number+" not found in Orders table");     
        prep.close();
       }
       catch(SQLException sqle)
       {
        messageLabel.setText("Error during lookup : "+sqle.getMessage());       
       }
 
Example: Add a record to the database from information on the screen.  Month, day, year are JTextFields.

       //
        // retrieve and convert data into local variables
        //
        String product = (String)orderProductField.getSelectedItem();
        String strquantity = orderQuantityField.getText();
        String strprice = orderPriceField.getText();
        String phone = orderPhoneField.getText();
        String monthstr = orderMonthField.getText();
        String yearstr = orderYearField.getText();
        String daystr = orderDayField.getText();
        int month, day, year;
 
       short quantity = 0;;
        double price = 0;
       
        try{
          quantity = Short.parseShort(strquantity);
        }
        catch(NumberFormatException e)
        {
         messageLabel.setText("Invalid entry in quantity field, must be a number");
         return;
        }
        try{
          price = Double.parseDouble(strprice);
        }
        catch(NumberFormatException e)
        {
         messageLabel.setText("Invalid entry in price field, must be a number");
         return;
        }
       
        try{
          month = Integer.parseInt(monthstr)-1; // make 0 relative
          day = Integer.parseInt(daystr);
          year = Integer.parseInt(yearstr);
        }
        catch(NumberFormatException e)
        {
         messageLabel.setText("Invalid entry date field");
         return;
        }
        //

        // Create an SQL date object, first create a Gregorian Calendar, then the date
        //
        GregorianCalendar caldate = new GregorianCalendar(year, month, day, 0, 0, 0);
        java.sql.Date date = new java.sql.Date(caldate.getTimeInMillis());
        //
        // test data for consistency and accuracy
        //
        if(price < 0)
        {
         messageLabel.setText("Price must be greater than or equal to zero");
         return;
        }
        if(quantity < 0)
        {
         messageLabel.setText("Quantity must be greater than or equal to zero");
         return;
        }
        if(product.length() <= 0)
        {
         messageLabel.setText("Product name cannot be blank");
         return;
        }
        if(phone.length() <= 0)
        {
         messageLabel.setText("Customer phone cannot be blank");
         return;
        }
        //
        //  create and execute a prepared statement
        //
        try{
          PreparedStatement prep = con.prepareStatement("INSERT INTO orders (CustomerPhone, ProductName, Quantity, PriceEach, OrderDate) Values(?, ?, ?, ?, ?)");
          prep.setString(1, phone);
          prep.setString(2,product);
          prep.setShort(3,quantity);
          prep.setDouble(4,price);
          prep.setDate(5,date);
          int result = prep.executeUpdate();
          if(result == 1)
             messageLabel.setText("New record added to the order table");
          else
             messageLabel.setText("Unable to add to the order table");
          prep.close(); // close the PreparedStatement
         }
         catch (SQLException e)
         {
          messageLabel.setText("Unable to order table : "+e.getMessage());
         }