90 likes | 113 Views
Explore Java's Date and Calendar classes, understand formatting, time zones, and practical tips for effective date and time handling in Java applications. Learn how to manipulate, format, and compare dates with examples. Discover useful utilities and explore Joda-Time for advanced time processing.
E N D
JAC444: Dates Tim McKenna Seneca@York
Dates, Calendars, and what year is this? • Java tries to take an OOD approach to“when is now?” • import java.util.*; // get util package • Date class – represents a point in time • Calendar class – a general way to organize time • java.GregorianCalendar –a specific way to organize time.
Date and Time • current date and time (in milliseconds)after January 1, 1970 00:00:00 GMT • long ms = System.currentTimeMillis( ) • milliseconds as a date & time object • java.util.Date date = new Date(); • Date is mostly deprecated because… • is a Date created at this moment here the same as one created in Australia? same ms but different date/time to us • Date assumes local time zone!
GregorianCalendar • GregorianCalendar extends Calendar • captures ms timestamp and time zone • constructors can create current or other date • getTime( ) returns a Date object • get(Calendar.YEAR / MONTH / DATE / etc ) • set or add(Calendar.YEAR/etc , int ) • boolean gc1.after(gc2) or gc1.before(gc2) • Example: DateTime.java
GregorianCalendar caution • always follow one or more .set(Calendar.XXX) method calls with any .get(Calendar.XXX) call. • GregorianCalendar today = new GregorianCalendar(); // current datetoday.set(Calendar.HOUR_OF_DAY, 0);today.set(Calendar.MINUTE, 0);today.set(Calendar.SECOND, 0);today.get(Calendar.DATE); // update fields
GregorianCalendar alternative • see Joda-Time at http://joda-time.sourceforge.net/index.html • Stephen Colebourne is the Lead Technical Architect … see his presentation in a PDF • Joda-Time may be needed in applications that do a lot of date and time processing
GregorianCalendar utilities • Databrew in the bobjects package offers: • daysInterval()number of days difference between two local dates ignoring time of day. • timeInterval() – "days hh:mm:ss" difference • calendarInterval() – "yy-mm-dd hh:mm:ss" difference
Formatting Date and Time • java.text.SimpleDateFormat - constructors - date formatting symbols - format( ) • only works if set() was followed by get() • Example: FormatDateTime.java
Preset Formatters • java.text.DateFormat - the parent class of SimpleDateFormat • DateFormat constants: SHORT, MEDIUM, LONG, FULL • DateFormat static methods : getDateInstance( ), getTimeInstance( ), getDateTimeInstance( ) retrieve normal format for that system • Example: DefaultFormats.java