Format Date

In real life application we have to format the Date as in user interface we have to display Date in some other format while our database stores it in a different format. To keep sync between those two formats we have to change the date format.

Default toString() method of Date prints ‘Sun Dec 06 09:42:09 IST 2015’ which is in ‘EEE MMM dd HH:mm:ss zzz yyyy’ format. There are lot of variations based on the locale are there.

To format the Date, java has SimpleDateFormat class which extends abstract DateFormat class. This class provides method to format the Date as well as parse the valid Date String to Date instance.

So, lets check simple example to get a formatted Date String from a Date Object.

public class FormatDate {

    public static void main(String args[]) {
        Date currentDate = new Date();
        System.out.println(currentDate);

        String dateFormat = "dd-MM-yyyy HH:mm";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        String formattedString = simpleDateFormat.format(currentDate);

        System.out.println("Formatted String of current date :" +formattedString);
    }
}

Above code will have output something like,

Sun Dec 06 10:47:38 IST 2015
Formatted String of current date :06-12-2015 10:47

So, this is a simple example of formatting the date. There are lot of other date patterns like dd.MM.yyyy, yyyy-dd-MM etc.

Kindly note that,

“SimpleDateFormat is not synchronized and so not thread safe. Better to create individual instance of SimpleDateFormat for every thread.”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s