Search code examples
javadatetimejava-6

How to get current date time in the format 2019101620000583?


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.


Solution

  • java.time

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

    ISO 8601

    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:

    • insert a T between the date portion and the time-of-day portion.
    • Append a 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


    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.

    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?

    Table of which java.time library to use with which version of Java or Android