Friday, 25 June 2010

Displaying the Date

I always always get in trouble when using Date, because of the huge number of deprecated methods it has. We should use Calendar almost exclusively.

Here's a simple example of a bad way and a good way to display a nice date:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DisplayDate
{

    public static void main(String args[]) 
    {
        // worse way
        Date myDate = new Date();
        int month = myDate.getMonth();
        int year = myDate.getYear();
        int day = myDate.getDate();
        System.out.println("Current date : " +
            day + "/" + (month + 1) + "/"
            + (year + 1900));
        Calendar cal = Calendar.getInstance();

        // bad way
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_MONTH);
        System.out.println("Current date : " +
            day + "/" + (month + 1) + "/" + year);

        // good way
        SimpleDateFormat simpleDateFormat = 
            new SimpleDateFormat("dd/MM/yyyy");
        String s =
           simpleDateFormat.format(cal.getTime());
        System.out.println("Current date : " + s);

    }
}

References

Javadoc - SimpleDateFormat
http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

No comments:

Post a Comment