Tuesday, September 27, 2011

How to Parse String into Date

After creating the DAO (Data Access Object) of Equipment History Software there is one interesting thing that Ar-Rohman Software House Team have learned. The thing is Parsing String Data Type into Date Data Type. As we know that basically all programs, software, or applications input are usually using character (char, String, etc.) or numbers (int, float, etc.). What if it input in the Date data type form ? Here's the tutorial to parse String data type into Date data type using Java.

Parsing String Into Date Listing Program

public class ParsingStringDateTest { 
public static void main(String args[]) throws ParseException{
DateFormat dateFormat;
Date tgl;

dateFormat = new SimpleDateFormat("dd-MM-yyyy");
tgl = (Date)dateFormat.parse("1-2-2011");
System.out.println(tgl); 
}
Explanation :
1. Creating DateFormat variable type. For example the variable named with dateFormat
DateFormat dateFormat;
DateFormat data type is used to make time field value for the implementation of date and time formatting.

2. Creating Date variable type as a input storage. For example the variable named with tgl
Date tgl;

3. Creating SimpleDateFormat(String formatWaktu) new object and store it in dateFormat variable
dateFormat = new SimpleDateFormat(“dd-MM-yyyy”);
SimpleDateFormat data type using pattern that given by String formatWaktu parameter which later filled with “dd-MM-yyyy”.

4. Parsing String tanggal input which later stored in tgl variable
tgl = (Date)dateFormat.parse(“1-2-2011”);

5. Done, now just see the result by typing the following code,
System.out.println(tgl);

How, it’s easy right ? Please don’t forget to try it. More about about the codes that we have used above can be viewed at http://download.oracle.com/javase/6/docs/.

0 comments:

Post a Comment

If you have something to say about this post, please fell free to write it in the comment form below. We will reply to all comments as soon as possible. Thanks ...