Skip to content
Advertisement

Generate a current datestamp in Java

What is the best way to generate a current datestamp in Java?

YYYY-MM-DD:hh-mm-ss

Advertisement

Answer

Using the standard JDK, you will want to use java.text.SimpleDateFormat

Date myDate = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
String myDateString = sdf.format(myDate);

However, if you have the option to use the Apache Commons Lang package, you can use org.apache.commons.lang.time.FastDateFormat

Date myDate = new Date();
FastDateFormat fdf = FastDateFormat.getInstance("yyyy-MM-dd:HH-mm-ss");
String myDateString = fdf.format(myDate);

FastDateFormat has the benefit of being thread safe, so you can use a single instance throughout your application. It is strictly for formatting dates and does not support parsing like SimpleDateFormat does in the following example:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd:HH-mm-ss");
Date yourDate = sdf.parse("2008-09-18:22-03-15");
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement