270

How to get timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Timestamp());

This is what I have, but Timestamp() requires an parameters...

riccardo.cardin
  • 7,971
  • 5
  • 57
  • 106
user3388884
  • 4,748
  • 9
  • 25
  • 34
  • preparedStatement.setTimestamp(1, new Timestamp(System.currentTimeMillis())); – Rajat Dec 12 '18 at 05:41
  • What error are you getting? – Robert Columbia Dec 24 '18 at 16:39
  • FYI, the terribly troublesome old date-time classes such as `SimpleDateFormat` and `java.sql.Timestamp` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 24 '18 at 20:01

9 Answers9

265

Replace

new Timestamp();

with

new java.util.Date()

because there is no default constructor for Timestamp, or you can do it with the method:

new Timestamp(System.currentTimeMillis());
Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 16
    FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html) and `java.sql.Timestamp` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Dec 24 '18 at 20:01
  • I used: `new Date().getTime();` – aqteifan Nov 11 '21 at 19:18
230

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new java.util.Date());

This will get you the current date in the format specified.

Deepak Rai
  • 2,163
  • 3
  • 21
  • 36
dimoniy
  • 5,820
  • 2
  • 24
  • 22
  • 5
    This helped me out and I made some changed so I don't have to import `new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date())` – Pini Cheyni Dec 20 '15 at 12:47
  • Better `new SimpleDateFormat("yyyy.MM.dd HH:mm:ss").format(new Date())`; – Zon Jul 25 '17 at 05:55
  • This is a very helpful answer. Thank you. – Arefe Mar 16 '21 at 11:39
  • 4
    SimpleDadeFormat is not thread safe, make sure you are not using it in multithreading environment. Once I overlooked this and it was giving unpredictable results when two dates were compared. – Slavomir Apr 21 '21 at 05:25
99

tl;dr

Use only modern java.time classes. Never use the terrible legacy classes such as SimpleDateFormat, Date, or java.sql.Timestamp.

ZonedDateTime                    // Represent a moment as perceived in the wall-clock time used by the people of a particular region ( a time zone).
.now(                            // Capture the current moment.
    ZoneId.of( "Africa/Tunis" )  // Specify the time zone using proper Continent/Region name. Never use 3-4 character pseudo-zones such as PDT, EST, IST. 
)                                // Returns a `ZonedDateTime` object. 
.format(                         // Generate a `String` object containing text representing the value of our date-time object. 
    DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" )
)                                // Returns a `String`. 

Or use the JVM’s current default time zone.

ZonedDateTime
.now( ZoneId.systemDefault() )
.format( DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" ) )

java.time & JDBC 4.2

The modern approach uses the java.time classes as seen above.

If your JDBC driver complies with JDBC 4.2, you can directly exchange java.time objects with the database. Use PreparedStatement::setObject and ResultSet::getObject.

Use java.sql only for drivers before JDBC 4.2

If your JDBC driver does not yet comply with JDBC 4.2 for support of java.time types, you must fall back to using the java.sql classes.

Storing data.

OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;  // Capture the current moment in UTC.
myPreparedStatement.setObject( … , odt ) ;

Retrieving data.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

The java.sql types, such as java.sql.Timestamp, should only be used for transfer in and out of the database. Immediately convert to java.time types in Java 8 and later.

java.time.Instant

A java.sql.Timestamp maps to a java.time.Instant, a moment on the timeline in UTC. Notice the new conversion method toInstant added to the old class.

java.sql.Timestamp ts = myResultSet.getTimestamp( … );
Instant instant = ts.toInstant(); 

Time Zone

Apply the desired/expected time zone (ZoneId) to get a ZonedDateTime.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

Formatted Strings

Use a DateTimeFormatter to generate your string. The pattern codes are similar to those of java.text.SimpleDateFormat but not exactly, so read the doc carefully.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu.MM.dd.HH.mm.ss" );
String output = zdt.format( formatter );

This particular format is ambiguous as to its exact meaning as it lacks any indication of offset-from-UTC or time zone.

ISO 8601

If you have any say in the matter, I suggest you consider using standard ISO 8601 formats rather than rolling your own. The standard format is quite similar to yours. For example:
2016-02-20T03:26:32+05:30.

The java.time classes use these standard formats by default, so no need to specify a pattern. The ZonedDateTime class extends the standard format by appending the name of the time zone (a wise improvement).

String output = zdt.toString(); // Example: 2007-12-03T10:15:30+01:00[Europe/Paris]

Convert to java.sql

You can convert from java.time back to java.sql.Timestamp. Extract an Instant from the ZonedDateTime.

New methods have been added to the old classes to facilitate converting to/from java.time classes.

java.sql.Timestamp ts = java.sql.Timestamp.from( zdt.toInstant() );

Table of date-time types in Java (both legacy and modern) and in standard SQL


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 2
    So what is The Right Way to get the current wall clock time stamp in format "yyyy.MM.dd.HH.mm.ss"? Without explicitly specifying hard-coded string of my local time zone? That's what topic starter was asking, and I could not find it in your answer... – t7ko Jan 10 '20 at 05:35
  • 1
    @t7ko I added a line of example code to the *tl;dr* section showing how to ask explicitly for the JVM’s current default time zone. Calling `now()‘ without any arguments does the same but is not clear if you meant to use the default or if you were ignorant or forgetful about the crucial issue of time zone. – Basil Bourque Jan 10 '20 at 07:17
  • 1
    @BasilBourque very compact and pure +1. – Lunatic Nov 29 '22 at 13:48
35

Use modern java.time classes if you use java 8 or newer.

String s = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());

Basil Bourque's answer is pretty good. But it's too long. Many people would have no patience to read it. Top 3 answers are too old and may mislead Java new bee .So I provide this short and modern answer for new coming devs. Hope this answer can reduce usage of terrible SimpleDateFormat.

gzc
  • 8,180
  • 8
  • 42
  • 62
32

You can make use of java.util.Date instead of Timestamp :

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
Kakarot
  • 4,252
  • 2
  • 16
  • 18
10

You can use the following:

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result:

1539594988651
halfer
  • 19,824
  • 17
  • 99
  • 186
Phoenix
  • 1,470
  • 17
  • 23
  • It doesn’t have the string format asked for. Also I’m afraid that the only thing it adds to a couple of similar answers, is needless complication… – Ole V.V. Oct 15 '18 at 10:24
7

A more appropriate approach is to specify a Locale region as a parameter in the constructor. The example below uses a US Locale region. Date formatting is locale-sensitive and uses the Locale to tailor information relative to the customs and conventions of the user's region Locale (Java Platform SE 7)

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss", Locale.US).format(new Date());
user3144836
  • 4,060
  • 3
  • 27
  • 27
  • 2
    No such thing as “Locale Zone”. I suspect your are confusing `Locale` and time zone which are unrelated. `Locale` controls the cultural norms for formatting and the human language used for name of month/day. The time zone adjusts the date-time representation to be appropriate to some region’s [wall-clock time](https://en.wikipedia.org/wiki/Wall_clock_time). In the case of this Question, Locale is irrelevant as there are no formatting issues with which to apply cultural norms nor are there any names of month/day to localize to any particular human language. – Basil Bourque Feb 20 '16 at 07:35
  • @BasilBourque Thank you for your input. I've updated the answer to be more explicit – user3144836 Feb 23 '16 at 02:02
2

I am Using this

String timeStamp = new SimpleDateFormat("dd/MM/yyyy_HH:mm:ss").format(Calendar.getInstance().getTime());
System.out.println(timeStamp);
Anuj Bansal
  • 117
  • 5
0

Use the following strategy.

import java.sql.Timestamp;

Timestamp today = new Timestamp(System.currentTimeMillis())


 
Sandun Susantha
  • 1,010
  • 1
  • 10
  • 11
  • It does not answer the question asked. And using the `Timestamp` class is not recommended. It’s a very poorly designed class and long outdated. Use java.time. See [the answer by Basil Bourque](https://stackoverflow.com/a/35520573/5772882). – Ole V.V. Mar 03 '23 at 19:17
  • Also it’s already proposed in two existing answers including the accepted one. – Ole V.V. Mar 03 '23 at 19:25