13

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

YYYY-MM-DD:hh-mm-ss

Trastle
  • 5,155
  • 6
  • 26
  • 20
  • "when not using a database"? What?? Do you normally query a database to retrieve the current time? – John Millikin Sep 19 '08 at 03:04
  • Do you want a String in that format or some sort of timestamp/date object? – sblundy Sep 19 '08 at 03:04
  • JohnMilikan: Inefficient tho' 'tis, you can select current date from sysibm.sysdummy1 (that's the DB2 variant, I cna't remember what Oracles dummy tables are called). You're right though, that's not the way I'd do it. – paxdiablo Sep 19 '08 at 03:13
  • I was trying to say that the data I am writing out is not being timestamped for me when I write it into a table. Also I was not wanting to use and Language packs from external vendors. Thanks very much for your help. I'll also try to be a bit more concise with my questions in future. Cheers. – Trastle Sep 19 '08 at 05:18

5 Answers5

27

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.
  • 7,625
  • 4
  • 27
  • 24
8
Date d = new Date();
String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d);
System.out.println (formatted);
John Millikin
  • 197,344
  • 39
  • 212
  • 226
1

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.

Community
  • 1
  • 1
sblundy
  • 60,628
  • 22
  • 121
  • 123
0

SimpleDateFormatter is what you want.

Michael Neale
  • 19,248
  • 19
  • 77
  • 109
0
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.

Walter Rumsby
  • 7,435
  • 5
  • 41
  • 36