I am new to Java. I am trying to store current date time in long format, like 2019110820000583.
I tried using System.currentTimeMillis()
but it doesn't give date and time combined. It gives me result like 1573205716048
.
Get the current moment in UTC.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
Define a formatting pattern for your desired output.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) ;
Generate a String with text in your desired format.
String output = odt.format( f ) ;
For a time zone, similar to code above but use ZonedDateTime
in place of OffsetDateTime
.
ZonedDateTime.now( ZoneId.of( "America/Montreal" ) )
Tip: Generally best to use the standard ISO 8601 formats when serializing date-time values as text. To comply with the “basic” version of ISO 8601:
T
between the date portion and the time-of-day portion. Z
for a moment in UTC. Otherwise append the offset.So this:
DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssXXXXX" )
See this full example run live at IdeOne.com.
OffsetDateTime odt = OffsetDateTime.now( ZoneOffset.UTC ) ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmssXXXXX" ) ;
String output = odt.format( f ) ;
odt.toString(): 2019-11-09T04:38:47.972145Z
output: 20191109T043847Z
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
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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?