3. Dates and Times

Introduction

//----------------------------------------------------------------------------------
// use a calendar to compute year, month, day, hour, minute, and second values.
GregorianCalendar calendar = new GregorianCalendar();
System.out.println("Today is day " + calendar.get(Calendar.DAY_OF_YEAR) + " of the current year.");
//----------------------------------------------------------------------------------

Finding Today's Date

//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar();
int day = calendar.get(Calendar.DATE);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar();
System.out.println("The current date is "
    + calendar.get(Calendar.DATE) + " "
    + (calendar.get(Calendar.MONTH) + 1) + " "
    + calendar.get(Calendar.YEAR));
//=> The current date is 1998 04 28
//----------------------------------------------------------------------------------

Converting DMYHMS to Epoch Seconds

//----------------------------------------------------------------------------------
// create a calendar with current time and time zone
GregorianCalendar calendar = new GregorianCalendar();
// set time zone
calendar.setTimezone(zone);
// set date fields
calendar.set(field, value);
// get time in seconds
long time = calendar.getTime().getTime() / 1000;
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
long time = calendar.getTime().getTime() / 1000;
//----------------------------------------------------------------------------------
// day is day in month (1-31)
// month is month in year (1-12)
// year is four-digit year e.g., 1967
// hour, minute and second represent UTC time 
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.set(year, month - 1, day, hour, minute, second);
long time = calendar.getTime().getTime() / 1000;
//----------------------------------------------------------------------------------

Converting Epoch Seconds to DMYHMS

//----------------------------------------------------------------------------------
// create a calendar with current time and time zone
GregorianCalendar calendar = new GregorianCalendar();
// set time
calendar.setTime(new Date(time * 1000));
// get date fields
int day = calendar.get(Calendar.DATE);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(new Date(time * 1000));
System.out.println("Dateline: "
    + calendar.get(Calendar.HOUR_OF_DAY) + ":"
    + calendar.get(Calendar.MINUTE) + ":"
    + calendar.get(Calendar.SECOND) + "-"
    + calendar.get(Calendar.YEAR) + "/"
    + (calendar.get(Calendar.MONTH) + 1) + "/"
    + calendar.get(Calendar.DATE));
//----------------------------------------------------------------------------------

Adding to or Subtracting from a Date

//----------------------------------------------------------------------------------
long now, difference;
long when = now + difference
long then = now - difference
//----------------------------------------------------------------------------------
// any field of a calendar is incrementable via add() method
GregorianCalendar calendar = new GregorianCalendar(year, month, day, hour, minute, second);
calendar.add(Calendar.DATE, dayOffset);
calendar.add(Calendar.HOUR_OF_DAY, hourOffset);
calendar.add(Calendar.MINUTE, minuteOffset);
calendar.add(Calendar.SECOND, secondOffset);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DATE);
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
second = calendar.get(Calendar.SECOND);
//----------------------------------------------------------------------------------
long birthTime = 96176750;         // 18/Jan/1973, 3:45:50 am
long interval = 5 +                // 5 second
                17 * 60 +          // 17 minute
                2  * 60 * 60 +     // 2 hour
                55 * 60 * 60 * 24; // and 55 day
Date then = new Date(birthTime + interval);
SimpleDateFormat format = new SimpleDateFormat();
System.out.println("Then is " + format.format(then));
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.set(1973, 0, 18, 3, 45, 50);
calendar.add(Calendar.DATE, 55);
calendar.add(Calendar.HOUR_OF_DAY, 2);
calendar.add(Calendar.MINUTE, 17);
calendar.add(Calendar.SECOND, 5);
SimpleDateFormat format = new SimpleDateFormat();
System.out.println("To be precise " + format.format(calendar.getTime()));
//----------------------------------------------------------------------------------

Difference of Two Dates

//----------------------------------------------------------------------------------
long recent, earlier;
long difference = recent - earlier;
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar();
// convert first date to time
calendar.set(year1, month1, day1);
Date date1 = calendar.getTime();
// convert second date to time
calendar.set(year2, month2, day2);
Date date2 = calendar.getTime();
// compute difference
long difference = Math.abs(date2.getTime() - date1.getTime());
long days = difference / (1000 * 60 * 60 * 24);
//----------------------------------------------------------------------------------
long bree = 361535725; // 16 Jun 1981, 4:35:25
long nat  =  96201950; // 18 Jan 1973, 3:45:50

long difference = bree - nat;
System.out.println("There were " + difference + " seconds between Nat and Bree");

long seconds =  difference % 60;
difference  = (difference - seconds) / 60;
long minutes =  difference % 60;
difference  = (difference - minutes) / 60;
long hours   =  difference % 24;
difference  = (difference - hours)   / 24;
long days    =  difference % 7;
long weeks   = (difference - days)    /  7;

System.out.println("weeks " + weeks + ", days " + days + ", "
    + hours + ":" + minutes + ":" + seconds);
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
calendar.set(1981, 5, 16); // 16 Jun 1981
Date date1 = calendar.getTime();
calendar.set(1973, 0, 18); // 18 Jan 1973
Date date2 = calendar.getTime();
long difference = Math.abs(date2.getTime() - date1.getTime());
long days = difference / (1000 * 60 * 60 * 24);
System.out.println("There were " + days + " days between Nat and Bree");
//----------------------------------------------------------------------------------

Day in a Week/Month/Year or Week Number

//----------------------------------------------------------------------------------
// create a calendar with current time and time zone
GregorianCalendar calendar = new GregorianCalendar();
// set time
calendar.setTime(new Date(time * 1000));
// get date fields
int monthDay = calendar.get(Calendar.DAY_OF_MONTH);
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
int yearDay = calendar.get(Calendar.DAY_OF_YEAR);
int yearWeek = calendar.get(Calendar.WEEK_OF_YEAR);
//----------------------------------------------------------------------------------
// create a calendar with given year, month and day
GregorianCalendar calendar = new GregorianCalendar(year, month, day);
int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
int yearDay = calendar.get(Calendar.DAY_OF_YEAR);
int yearWeek = calendar.get(Calendar.WEEK_OF_YEAR);
//----------------------------------------------------------------------------------
int year  = 1981;
int month = 6;
int day   = 16;

GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);

Date date = calendar.getTime();
SimpleDateFormat format1 = new SimpleDateFormat("mm/dd/yy");
SimpleDateFormat format2 = new SimpleDateFormat("EEEE");
System.out.println(format1.format(date) + " was a " + format2.format(date));

int week = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("in the week number " + week);
//----------------------------------------------------------------------------------

Parsing Dates and Times from Strings

//----------------------------------------------------------------------------------
String raw = "1998-06-03";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
    Date date = format.parse(raw);
    long time = time.getTime();
} catch (ParseException ex) {
    // bad date
}
//----------------------------------------------------------------------------------
SimpleDateFormat in = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat out = new SimpleDateFormat("MM/dd/yyyy");
try {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    String line;
    while ((line = input.readLine()) != null) {
        try {
            Date date = in.parse(line);
            System.out.println("Date was " + out.format(date));
        } catch (ParseException ex) {
            System.err.println("Bad date string: " + line);
        }
    }
} catch (IOException ex) {}
//----------------------------------------------------------------------------------

Printing a Date

//----------------------------------------------------------------------------------
DateFormat format;
String string = format.format(new Date(time));
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar(1973, 0, 18, 3, 45, 50);
DateFormat format = DateFormat.getInstance();
System.out.println("Default locale format gives: " + format.format(calendar.getTime()));
//----------------------------------------------------------------------------------
GregorianCalendar calendar = new GregorianCalendar(1973, 0, 18, 3, 45, 50);
SimpleDateFormat format = new SimpleDateFormat("E M d hh:mm:ss z yyyy");
System.out.println("Customized format gives: " + format.format(calendar.getTime()));
//----------------------------------------------------------------------------------

High-Resolution Timers

//----------------------------------------------------------------------------------
long t0 = System.currentTimeMillis();
// do your operation here
long t1 = System.currentTimeMillis();
long elapsed = t1-t0;
// elapsed is the number of milliseconds between t0 and t1
//----------------------------------------------------------------------------------
System.out.println("Press return when ready");
long before = System.currentTimeMillis();
try {
    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
    input.readLine();
} catch (IOException ex) {}
long after = System.currentTimeMillis();
long elapsed = (after - before) / 1000;
System.out.println("You took " + elapsed + " seconds.");
//----------------------------------------------------------------------------------
// take mean sorting time
int size = 500;
int number = 100;
long time = 0;

for (int i=0; i<number; i++) {
    double[] array = new double[size];
    for (int j=0; j<size; j++)
        array[j] = Math.random();

    // sort it
    long t0 = System.currentTimeMillis();
    Arrays.sort(array);
    long t1 = System.currentTimeMillis();
    time += (t1 - t0);
}

System.out.println("On average, sorting " + size + " random numbers takes " +
    (time / number) + " milliseconds");
//----------------------------------------------------------------------------------

Short Sleeps

//----------------------------------------------------------------------------------
long delay; // time to sleep in milliseconds
try {
    Thread.sleep(delay);
} catch (InterruptedException ex) {}
//----------------------------------------------------------------------------------
// excerpt from more complete exemple from PLEAC@@_1.5
Reader input;
int ch;
while ((ch = input.read()) != -1) {
    System.out.print((char) ch);
    try {
        Thread.sleep(delay);
    } catch (InterruptedException ex) {}
}
//----------------------------------------------------------------------------------

Program: hopdelta