Simple date formatter example

In this section of simple date formatter example we are
going to describe you how you can use different constructors of SimpleDateFormat
class to convert the date into the specified format. There are various constructors of SimpleDateFormat
class.
Date todaysDate = new java.util.Date(); creates
a new instance of Date with the current date and time value.
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
Above lines of code formats the date object into the "yyyy-MM-dd
HH:mm:ss" format.
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
In the above code we have formatted the date into
"yyyy-MM-dd" format.
Here is the full example code of SimpleFormatDate.java as
follows:
SimpleFormatDate.java
import java.util.Date;
import java.text.SimpleDateFormat;
public class SimpleFormatDate
{
public static void main(String args[]){
Date todaysDate = new java.util.Date();
// Formatting date into yyyy-MM-dd HH:mm:ss e.g 2008-10-10 11:21:10
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
// Formatting date into yyyy-MM-dd e.g 2008-10-10
formatter = new SimpleDateFormat("yyyy-MM-dd");
formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
// Formatting date into MM/dd/yyyy e.g 10/10/2008
formatter = new SimpleDateFormat("MM/dd/yyyy");
formattedDate = formatter.format(todaysDate);
System.out.println("Formatted date is ==>"+formattedDate);
}
}
|
Save SimpleFormatDate.java and compile it with the javac
command.
Output:
C:\DateExample>javac SimpleFormatDate.java
C:\DateExample>java SimpleFormatDate
Formatted date is ==>2008-10-10 13:03:54
Formatted date is ==>2008-10-10
Formatted date is ==>10/10/2008
|
Download Source Code

|