Home‎ > ‎Applied Core Java‎ > ‎Introduction‎ > ‎

Convert a Date to String

Problem :

A date is usually entered as a String from a UI. How I can convert a String into java.util.Date object and vice-versa.

Solution :

The DateFormat class, found in java.text package is an abstract class for date/time formatting .It provides a foundation for subclass such as SimpleDateFormat to format and parse dates or time in a language-independent manner.The SimpleDateFormat class, found in java.text package, is concrete subclass of the DateFormat class , allows converting a Date to String and vice-versa . Formats/Parses a date or time, which is the standard milliseconds since 24:00 GMT, Jan 1, 1970

Program :

Step 1 - Coding

Create a text file c:\sunilos\TestDateFormat.java  and copy below contents.

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

/*
 * A program that converts a Date to String and vice-versa
*/

public class TestDateFormat {

    /**
     * Keyword "throws Exception"  is required to avoid exception handling during parsing string
     * You will learn exception handling in other chapters
     */
    public static void main(String[] args) throws Exception {
      
                    //Specify required date format. Here it Day-Month-Year

        SimpleDateFormat sdf =  new SimpleDateFormat("dd-MM-yyyy");
       
        Date d= new Date(); //Get system date
       
        //Convert Date object to string
        String strDate = sdf.format(d);
        System.out.println("Formated String is " + strDate);
       
        //Convert a String to Date
        d  = sdf.parse("31-12-2009");
       
        System.out.println("Converted Date is : " +d);
    }

}

Step 2 - Deployment

  1. Create a folder 'c:\sunilos'. 
  2. Create or copy TestDateFormat.java  into 'c:\sunilos' folder.
  3. Open your command prompt and go to  'c:\sunilos'
  4. Compile TestDateFormat.java with help of 
    • javac TestDateFormat.java command. Compiled class file will be created in the same folder
  5. Congratulations!! your Java program is ready to serve.

Step 3 - Testing

  1. Make sure you are on Command Prompt under c:\sunilos directory
  2. Now start your java program from command prompt with help of 
    • java TestFormat command.

Output

Formated String is 03-04-2009
Converted Date is : Thu Dec 31 00:00:00 GMT+05:30 2009


FAQ

Q. Can I convert my date into other formats ?

A. Yes below are few sample formats:

Date and Time Pattern Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700

See SimpleDateFormat for more details.
 


<<Previous | Next>>
ċ
TestDateFormat.java
(1k)
nakul shukla,
Apr 3, 2009, 2:36 AM
Comments