DateTime.java

Download DateTime.java

  1: // DateTime.java - A demonstration of several Java date and time
  2: // classes and techniques.  (Note SQL databases use time and date
  3: // formats defined by classes in the package java.sql.)
  4: //
  5: // Written 1999 by Wayne Pollock, Tampa, Florida USA.
  6: // Updated 2006 to use Scanner, and to show SimpleDateFormat class
  7: 
  8: import java.util.*;   // for Date and Calendar
  9: import java.text.*;   // for DateFormat and TimeFormat
 10: 
 11: class DateTime
 12: {
 13:    private static Date now = new Date();
 14: 
 15:    public static void main ( String [] args )
 16:    {
 17: // *************************************************************************
 18:       // Here's an example showing how to time something:
 19: 
 20:       System.out.println( "\nStarting timer...." );
 21:       Date start = new Date();
 22: 
 23:       Scanner in = new Scanner( System.in );
 24:       System.out.print( "\tWhat is \"2 + 3\"? " );
 25:       String name = in.nextLine();
 26: 
 27:       Date end = new Date();
 28:       long duration = Math.round( (end.getTime() - start.getTime()) / 1000.0 );
 29:       System.out.println( "You took " + duration
 30:                          + " seconds to work that out!" );
 31: 
 32: // *************************************************************************
 33:       // Here's how to format a Date as a human-readable string:
 34: 
 35:       // One command to format both the date and time:
 36:       String dt = DateFormat.getDateTimeInstance().format( now );
 37:       System.out.println( "\nThe Date and time is now: " + dt + "." );
 38: 
 39:       // You can get the date and time strings seperately:
 40: 
 41:       String d1 = DateFormat.getDateInstance().format( now );
 42:       String t1 = DateFormat.getTimeInstance().format( now );
 43:       System.out.println( "\n\tDefault formats:" );
 44:       System.out.print( "At the tone the time will be " );
 45:       System.out.println( d1 + " " + t1 + " ...Beeeeep!" );
 46: 
 47:       // You can use SHORT, MEDIUM, LONG, or FULL formats too:
 48: 
 49:       String d2 = DateFormat.getDateInstance(DateFormat.FULL).format( now );
 50:       String t2 = DateFormat.getTimeInstance(DateFormat.SHORT).format( now );
 51:       System.out.println( "\n\tFULL date and SHORT time formats:" );
 52:       System.out.print( "At the tone the time will be " );
 53:       System.out.println( d2 + " " + t2 + " ...Beeeeep!" );
 54: 
 55: // *************************************************************************
 56:       // You can use SimpleDateFormat to format (or parse) dates and
 57:       // times in any format.  Here we format the current date as an
 58:       // RFC-5322 (formally RFC-2822) standard date and time string:
 59: 
 60:       SimpleDateFormat rfc2822Fmt = new SimpleDateFormat(
 61:           "EEE, dd MMM yyyy HH:mm:ss Z (zzz)" );
 62:       System.out.print( "\nRFC-2822 standard Date format for today: " );
 63:       System.out.println( rfc2822Fmt.format(now) );
 64: 
 65:       // Much of the world uses the flexible ISO-8601 formatted dates and times;
 66:       // web technology uses a (nearly identical) variant called RFC-3339:
 67: 
 68:       TimeZone tz = TimeZone.getTimeZone( "UTC" );
 69:       DateFormat iso8601Fmt = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm'Z'" );
 70:       iso8601Fmt.setTimeZone( tz );
 71:       System.out.print( "\nISO-8601 standard Date format for today: " );
 72:       System.out.println( iso8601Fmt.format(now) );
 73: 
 74: // *************************************************************************
 75:       // You can use a DateFormat object to convert a string to a Date object,
 76:       // (but you must use the right formats!):
 77: 
 78:       Date d = null;
 79:       DateFormat df = DateFormat.getDateTimeInstance(
 80:          DateFormat.SHORT, DateFormat.SHORT );
 81:       df.setLenient( true );  // May allow some sloppyness in user input.
 82: 
 83:       String someDate = df.format(now);
 84:       System.out.print( "\nEnter a date and time (e.g., \""
 85:                         + someDate + "\"): " );
 86:       for ( ; ; )
 87:       {
 88:          try
 89:          {  someDate = in.nextLine();
 90:             d = df.parse( someDate );
 91:             break;
 92:          }
 93:          catch ( ParseException pe )
 94:          {  System.out.print( "Invalid date and time format, "
 95:                              + "please try again: " );
 96:          }
 97:       }
 98: 
 99:       // The above code could be modified, to try several different
100:       // DateFormat objects, one aftert the other, and break out if
101:       // any of them match.  (Left as an exercise to the reader.)
102: 
103:       String d3 = DateFormat.getDateInstance( DateFormat.MEDIUM ).format( d );
104:       System.out.println( "\nThe date part of \"" + someDate +"\" is: " + d3 );
105:       String t3 = DateFormat.getTimeInstance( DateFormat.LONG ).format( d );
106:       System.out.println( "and the time part is: " + t3 + "." );
107: 
108:       // In production-quality code, consider not doing this at all.
109:       // Instead, use a GUI date-picker widget, or have separate inputs
110:       // for the month, day, and year (using drop-down lists, for example).
111: 
112: // *************************************************************************
113:       // Here's how to compare two Dates:
114: 
115:       if ( d.after( now ) )
116:          System.out.println( "(And that date is in the future!)" );
117:       else
118:          System.out.println( "(And that date is in the past!)" );
119: 
120: // *************************************************************************
121:       // You can use a Calendar object to get parts of a date, or to
122:       // construct a Date:
123: 
124:       Calendar today = Calendar.getInstance();  // or: new GregorianCalendar();
125:       today.setTime( now );
126: 
127:       // Which day of the week is it?  Here's how to find out:
128: 
129:       String weekday[] = new DateFormatSymbols().getWeekdays();
130:       String day = weekday[ today.get( Calendar.DAY_OF_WEEK ) ];
131:       System.out.println( "\n\nToday is " + day + "." );
132: 
133:       // Here's how to construct a date.  (Note you can use
134:       // Calendar.getTime() to convert to a Calendar to a Date):
135: 
136:       Calendar christmas = Calendar.getInstance(); //or new GregorianCalendar();
137:       christmas.set( today.get( Calendar.YEAR ), Calendar.DECEMBER, 25 );
138: 
139:       int daysLeft = christmas.get(Calendar.DAY_OF_YEAR)
140:                      - today.get(Calendar.DAY_OF_YEAR);
141:       System.out.println( "\nOnly " + daysLeft + " shopping days left "
142:                           + "until Christmas!" );
143:    }
144: }