Java current time formatted

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

FYI, the terribly troublesome old date-time classes such as SimpleDateFormat and java.sql.Timestamp are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

9 Answers 9

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

new Timestamp(System.currentTimeMillis()); 

FYI, the terribly troublesome old date-time classes such as java.util.Date and java.sql.Timestamp are now legacy, supplanted by the java.time classes built into Java 8 and later. See Tutorial by Oracle.

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.

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())

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.

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?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later — Part of the standard Java API with a bundled implementation.
  • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
  • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • Later versions of Android bundle implementations of the java.time classes.
  • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

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.

Источник

How to print the current time and date in ISO date format in java?

I am supposed to send the current date and time in ISO format as given below: ‘2018-02-09T13:30:00.000-05:00’ I have written the following code:

Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm"); SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.000'Z'"); System.out.println(formatter.format(date)); System.out.println(formatter1.format(date)); 
2018-04-30T12:02 2018-04-30T12:02:58.000Z 

But it is not printing as the format mentioned above. How can I get the -5:00 as shown in the format and what does it indicate?

Try it without single-quoting the Z in your second SimpleDateFormat. I think that’ll do it, but I can’t verify right now. When you single-quote it, you’re asking for just a literal Z.

2 Answers 2

In java 8 you can use the new java.time api:

OffsetDateTime now = OffsetDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ISO_DATE_TIME; System.out.println(formatter.format(now)); // e.g. 2018-04-30T08:43:41.4746758+02:00 

The above uses the standard ISO data time formatter. You can also truncate to milliseconds with:

OffsetDateTime now = OffsetDateTime.now().truncatedTo(ChronoUnit.MILLIS); 

Which yields something like (only 3 digits after the dot):

I can’t believe it’s this simple, but then again this is why they did away with the old date API. it was just too hard for most people to use +1.

@MadProgrammer Ah, I didn’t notice that, I think the first time I tested it just happened to have 3 digits by coincidence. This is the ISO date format constant though, so I hope this is an acceptable format too.

@JornVernee From my point of view, it should be, assuming who ever is receiving the data is using an appropriate parser, but that would become their issue 😉

It complies with ISO 8601 no matter the number of decimals, so it will probably work where it is to be used anyway.

 System.out.println(OffsetDateTime.now(ZoneId.of("America/Panama")).toString()); 

Just now I got this output:

To control that seconds are always printed with exactly three decimals:

 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSXXX"); OffsetDateTime now = OffsetDateTime.now(ZoneId.of("America/Panama")); System.out.println(now.format(formatter)); 

The first, the easy version will print enough groups of three decimals to render the full precision. It will also leave out the seconds completely if they happen to be 0.0. Both are probably OK because all of this is allowed within the ISO 8601 format that you asked for. So whoever receives the string should be happy anyway.

Please fill in your desired time zone where I used America/Panama. It’s best to give explicit time zone for predictable output.

I am using and recommending java.time , the modern Java date and time API. The SimpleDateFormat that you used is not only long outdated, it is also notoriously troublesome. java.time is so much nicer to work with.

What does -05:00 indicate?

-05:00 is an offset from UTC (or GMT, it is nearly the same thing). So your example string is probably from eastern time zone in North America or some other place in Central or Southern America (Cuba, Bolivia, to mention a few that use this offset for some of the year). More precisely -05:00 means that we’re using a clock that is 5 hours (and 0 minutes) behind UTC. So 2:12:46-05:00 denotes the same point in time as 7:12:46 UTC. If we only knew the time was 2:12:46 and didn’t know a time zone or offset, it would be very ambiguous. An offset is perfect for turning the time into an unambiguous point in time.

Источник

Читайте также:  Html css columns width
Оцените статью