Thursday, March 6, 2014

Dates and Times in Java

Java has good built-in support for working with dates and times.

3 primary classes:

java.util.Date - kind of deprecated. Use java.util.Calendar class
java.sql.Date
java.util.Calendar

Many of the methods in the java.util.Date class have become deprecated.

Finding Today's Date:

        Date today = new Date();
        System.out.println("Today is : " + today.toString());
       
        Calendar cal = Calendar.getInstance();
        System.out.println("Today is : " + cal.getTime().toString());

O/p:
Today is : Thu Mar 06 11:36:50 IST 2014
Today is : Thu Mar 06 11:36:50 IST 2014

Converting between Date and Calendar objects

// Date to Calendar conversion
Date myDate = new java.util.Date();
Calendar myCal = Calendar.getInstance();
myCal.setTime(myDate);

// Calendar to Date conversion
Calendar newCal = Calendar.getInstance();
Date newDate = newCal.getTime();

In most Java applications, you'll find uses of both the Date and Calendar classes; thus knowing how to convert from one to the other is something you want to be familiar with.

Best practice is, you create utility methods to perform these conversations so that you can convert from any place in your code with a simple method call.

public static Date calToDate(Calendar cal) {
          return cal.getTime();
}

public static Calendar dateToCal(Date date) {
          Calendar myCal = Calendar.getInstance();
          myCal.setTime(date);
          return myCal;
}


Printing Date/Time in a Given Format:

Java contains formattign classes that can be used to format a date into a desired format.

Example:
        import java.text.SimpleDateFormat;

        Date todaysDate = new Date();
        SimpleDateFormat formatter =

                                      new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
        String formattedString = formatter.format(todaysDate);
        System.out.println(formattedString);

o/p:
Thu, 06 Mar 2014 11:57:07

 

Using this format: "EEEE, d-MMM-yyyy HH:mm:ss a", 
o/p :
Thursday, 6-Mar-2014 11:55:07 AM

Using this format: "EEEE, dd-MMMM-yyyy HH:mm:ss a",
o/p:
Thursday, 06-March-2014 11:58:13 AM

Using Pre-defined format strings:

import java.text.DateFormat;

        DateFormat df = DateFormat.getDateInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
Mar 6, 2014


        DateFormat df = DateFormat.getTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
12:02:33 PM


        DateFormat df = DateFormat.getDateTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
Mar 6, 2014 12:02:56 PM

More useful things:

Calendar cal = Calendar.getInstance();

cal.getTimeZone().getDisplayName() - India Standard Time
cal.getTimeZone().toString() - sun.util.calendar.ZoneInfo
                     [id= "Asia/Calcutta", offset=19800000, dstSavings=0, useDaylight=false, transitions=6, lastRule=null]
cal.getTimeZone().getID() - Asia/Calcutta

Parsing Strings into Dates

        String dateString = "Jan 12, 1952 3:30:32 pm";
        DateFormat df = DateFormat.getDateTimeInstance();
        try {
            Date date1 = df.parse(dateString);
            System.out.println("Parsed Date: " + date1.toString());
        } catch (ParseException ex) {
            Logger.getLogger(DatesAndTimes.class.getName()).log(Level.SEVERE, null, ex);
        }

o/p:
Parsed Date: Sat Jan 12 15:30:32 IST 1952

The DateFormat object is used to parse a String and obtain a java.util.Date object.
 The java.sql.Date, java.sql.Time, and java.sql.Timestamp classes contain a static method called valueOf() which can also be used to parse simple date strings of the format "yyyy-mm-dd". This is very useful for converting dates you might use in SQL strings while using JDBC, into Date objects.     String date = "2000-11-01";
    java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);

Adding to or Substracting from a Date or Calendar:

If you are using Date object, the technique for adding or substracting dates is to first convert the object to a long value using the getTime() method of Date object.

The getTime() method returns the time as measured in milliseconds since the epoch. You then perofrm arithmetic on the long values and finally convert back to date objects.

        // date arithmetic using Date objects
        Date date = new Date();
        long time = date.getTime();
        time += 5*24*60*60*1000;
        Date futureDate = new Date(time);

You perform date arithmetic directly on Calendar objects using the add() method.
    
        // date arithmetic using Calendar objects
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DATE, 5);

Difference between Two Dates

        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long diff = time2 – time1;
        System.out.println("Difference in days = " + diff/(1000*60*60*24));

Usecase: Calculating expiry days for an item:

        public static void daysTillExpired(Date expDate) {
            Date currentDate = new Date();
            long expTime = expDate.getTime();
            long currTime = currentDate.getTime();
            long diff = expTime – currTime;
            return diff/(1000*60*60*24);
        }

Comparing Dates

        if (date1.equals(date2)) {
            System.out.println("dates are the same.");
        }
        else {
            if (date1.before(date2)) {
                System.out.println("date1 before date2");
            }
            else {
                System.out.println("date1 after date2");
            }
        }

The dates must be the same down to the millisecond level in order for the equals() method to return true.

The Date class also has an after() method, which is used similar to before() method to determine if the date on which it is called occurs after the date passed in as parameter.

Another useful method for comparing two dates is the compareTo() method of the Date class. It returns an integer value. 0 - indicates dates are equal.

Finding the day of week/month/year or week number:

        Calendar cal = Calendar.getInstance();
        System.out.println("Day of week: " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Month: " + cal.get(Calendar.MONTH));
        System.out.println("Year: " +  cal.get(Calendar.YEAR));
        System.out.println("Week number: " + cal.get(Calendar.WEEK_OF_YEAR));

Calculating elapsed time:

By calculating elapsed time, we can determine how long it takes to do something or how long a process takes to complete.

        long start = System.currentTimeMillis();
        // do some other stuff…
        long end = System.currentTimeMillis();
        long elapsedTime = end – start;

System.currentTimeMillis() method is the time since January 1, 00:00:00, 1970 in milliseconds.

JDK 1.5 adds a nanoTime() method to the System class, which gives even more precise timing, down to nano seconds.



No comments:

Post a Comment