How to Parse Dates from Strings
July 22, 2006 on 9:44 am | In Java |This example shows how to parse dates from strings using the
SimpleDateFormat class.
The pattern is specified in the constructor, but could also be done with the applyPattern(String pattern) method.
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class TestDate {
public static void main(String[] args) throws ParseException {
String s = "15-05-2005 5:55:55";
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = df.parse(s);
System.out.println(date);
}
}
This example should help ease the difficulty that all beginners seem to face when dealing with formatting
dates in Java.
Technorati Tags: Java, Programming
Related Posts:
- How to Format Dates for SQL in Java
- Validating a Date Field with RIFE
- Copy/paste command-line utilities
- Using Apache Axis in NetBeans 5.0
5 Comments »
RSS feed for comments on this post.
Leave a comment
Powered by blog.mu with Pool theme design by Borja Fernandez.


You may want to look at Joda-Time http://joda-time.sourceforge.net
Comment by Stephen Colebourne — 22 July 2006 #
Don’t forget to call date.setLenient(false) before calling parse to have a strict matching.
Without this, you can have strange result if your date string is a user input.
Comment by Franck Arnulfo — 23 July 2006 #
Ooops, call df.setLenient(false)
Comment by Franck Arnulfo — 23 July 2006 #
Thats so true I recall the amount of time it took me to google out a good example of how to parse a string into date format some years back.
There is a site nowadays called http://javaalmanac.com/ that provides some really nice examples of how to perform useful stuff in Java , its great time saver for beginners.
Comment by javed — 24 July 2006 #
Javed,
I sometimes refer to Java Almanac myself, for it is indeed an excellent resource.
Eddy
Comment by Eddy — 24 July 2006 #