How to convert date format in java.

How to convert date format in java.


Posted in : Core Java Posted on : November 23, 2010 at 5:45 PM Comments : [ 0 ]

In this example, you will see how to convert date format in java.

How to convert date format in java.

In this section, we will introduce how to convert a given date into required format.

The Date(string strDate) is constructor of Date class in java. It creates a date object and initializes it.  The Date class is available in java.util package. Here, string object str is a particular date which we wants to change in to another format.

The SimpleDateFormat(string strFormat) is a constructor of SimpleDateFormat class. It creates the object of SimpleDateFormat and initialize it. It is present in java.text package. The strFormat is date format, in which you wants to change. The SimpleDateFormat class use for formatting and parsing dates. It allows for formatting date into text , parsing text into date and normalization.

The format() is method of SimpleDateFormat class. It is used for format Date class object into date / time and appends it into the StringBuffer.

Code:
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatExmple {
    public static void main(String[] args) {
     // Create a Date object
     Date obDate = new Date("25-oct-1986");
     // Create string object
     String formatString = "EEE, MMM d, yy";
     System.out.println("Before changing : " + obDate);
     SimpleDateFormat obDateFormat = new SimpleDateFormat(formatString);
     System.out.println("After changing format   : "
	+ obDateFormat.format(obDate));
	}
}
Output
Before changing : Sat Oct 25 00:00:00 GMT+05:30 1986
After changing format : Sat, Oct 25, '86

Output:

Download this code.

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics