June 27, 2004

How to format a date in Java

Creating a java.util.Date gives you the date all right, but if you need to format it in a particular way, say, for a database query, you need to use a formatter, such as the SimpleDateFormat class. For example, this code turns today's date into the string "06-27-2004":

java.util.Date theDate = new java.util.Date;
java.text.SimpleDateFormat dateFormatter = 
       new java.text.SimpleDateFormat("MM-dd-yyyy");
String theFormattedDate = dateFormatter.format(theDate);

You can format it any way that you like. Check out Customizing Formats for more pattern options.

Technorati tags: Java | dates | formatting | formatting java dates | java.util.Date | Calendar | java.text.SimpleDateFormat | java.text.DateFormat |

src="http://feeds.feedburner.com/~s/ChaosMagnet?i=http://www.chaosmagnet.com/blog/archives/000452.html" type="text/javascript" charset="utf-8">
Posted by roadnick at June 27, 2004 02:56 PM | TrackBack

Comments

Post a comment









Remember personal info?