tags:

views:

1417

answers:

6

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

YYYY-MM-DD:hh-mm-ss

+7  A: 
Date d = new Date();
String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d);
System.out.println (formatted);
John Millikin
This example is missing the "new" keyword before SimpleDateFormat("yyyy...
jt
@jt thanks, fixed
John Millikin
Dislike code sections that don't have the requisite imports.
paxdiablo
A: 

SimpleDateFormatter is what you want.

Michael Neale
A: 

There's also

long timestamp = System.currentTimeMillis()

which is what new Date() (@John Millikin) uses internally. Once you have that, you can format it however you like.

sblundy
A: 

I think that you need to be a little more clear in your question. In particular, what data type do you want at the end of the process? A String?

A: 
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd:hh-mm-ss");

formatter.format(new Date());

The JavaDoc for SimpleDateFormat provides information on date and time pattern strings.

wrumsby
+14  A: 

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");
jt