Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a current datestamp in Java

Tags:

java

datestamp

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

YYYY-MM-DD:hh-mm-ss

like image 321
Trastle Avatar asked Sep 19 '08 02:09

Trastle


People also ask

What is the datatype for timestamp in Java?

The timestamp data type. The format is yyyy- MM -dd hh:mm:ss[. nnnnnnnnn]. Mapped to java.


2 Answers

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");
like image 188
jt. Avatar answered Sep 18 '22 18:09

jt.


Date d = new Date();
String formatted = new SimpleDateFormat ("yyyy-MM-dd:HH-mm-ss").format (d);
System.out.println (formatted);
like image 24
John Millikin Avatar answered Sep 18 '22 18:09

John Millikin