Date formatting in Java

Java provides different ways of formatting the dates. The Java date formatting can be performed by using the SimpleDateFormat class. You can also use the printf method to format dates in Java. Both of the ways are explained below.

Java printf method for Date formatting

You can use the printf method to format dates quite easily. Java supports date and time conversion characters that can be used with Java printf method to format dates. A list of those important characters is given below but first, let us show you how to use the printf with the date.

Getting current date time with printf

To get the current date and time, the example below uses string format function. The ‘c’ character with %t gets the current date and time and then printf method is used to display it, see below:

Experience this online

The output will be:

Current date/time: Sat Jan 15 18:48:38 PKT 2011

Current date in day, full month name, and year format example

The example displays the date in day, full month name and year format e.g. 13 March 2011. We used Date class object with printf Java method for that.

Experience this online

The output will be:

Current date: 15 January, 2011

The Printf List of characters to format date

Find the list of characters that can be used in string formatting and displayed with printf method.

Examples of Java Date formatting with SimpleDateFormat class

The example below shows how to format the date in Java. We will use the SimpleDateFormat class that is the part of java.text package. In real time applications, you have to format dates as per need like date formatting in dd/mm/yyyy or mm/dd/yyyy or Mon, day, year etc. to make the presentation of dates more readable and understandable to the users of the application. The Java

In real time applications, you have to format dates as per need like date formatting in dd/mm/yyyy or mm/dd/yyyy or Mon, day, year etc. to make the presentation of dates more readable and understandable to the users of the application. The Java

The Java Simple DateFormat is great for parsing and formatting the date.

Experience this online

The output will be:

Current Date in dd/MM/yyyy format: 15/01/2011

Current Date in MM/dd/yyyy format: 01/15/2011

Current Date and time in MM/dd/yyyy format: 01/15/2011 06:07:45

 

Related: Java date