developerlife.com (tm)
home -> Converting Date (and time) to/from String


Converting Date (and time) to/from String
Nazmul Idris, Mar 27 1999.

Description

There is a need at many times to get the Date from a String and also to turn a Date into a String. In Java2, you have to use the SimpleDateFormat class to do this. It allows you to:
  1. generate a String given a Date
  2. generate a Date given a String
You have to define the format in which the Date -> String conversion must happen. This is done by specifying the format string, eg: "YY MM DD", simply results the year, month and date to be output, all separated by spaces.

In Java2, there is no Time class, the time is a part of the date. If you just want to know the time, then the SimpleDateFormat string should be set to something like: "hh:mm:ss a zzz".

Code

import java.util.*;
import java.text.*;

//date code

 try{
     Date d = new Date();

     //this date format is very condusive to being used as a filename
     SimpleDateFormat sdf = new SimpleDateFormat (
         "yyyy_MM_dd.hh_mm_ss_a.zzz");

     String dateString = sdf.format(d);
     System.out.println( dateString );

     Date d2 = sdf.parse( dateString );
     System.out.println( d2.toString() );
 }
 catch(Exception e){
     System.out.println( e );
 }

 

 
Web developerlife.com
Click here to send comments/feedback
Copyright Nazmul Idris 1999-2006. All Rights Reserved.
Last updated June 24 2006.