Name a file in Java to include date and time stamp

前端 未结 3 1904
轮回少年
轮回少年 2020-12-12 07:31

I am exporting data into a file in a Java application using NetBeans. The file will have a hard coded name given by me in the code. Please find below the code.



        
3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-12 07:53

    tl;dr

    "Report" + "_" 
             + Instant.now()                               // Capture the current moment in UTC.
                      .truncatedTo( ChronoUnit.SECONDS )   // Lop off the fractional second, as superfluous to our purpose.
                      .toString()                          // Generate a `String` with text representing the value of the moment in our `Instant` using standard ISO 8601 format: 2016-10-02T19:04:16Z
                      .replace( "-" , "" )                 // Shorten the text to the “Basic” version of the ISO 8601 standard format that minimizes the use of delimiters. First we drop the hyphens from the date portion
                      .replace( ":" , "" )                 // Returns 20161002T190416Z afte we drop the colons from the time portion. 
             + ".pdf"
    

    Report_20161002T190416Z.pdf

    Or define a formatter for this purpose. The single-quote marks ' mean “ignore this chunk of text; expect the text, but do not interpret”.

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "'Report_'uuuuMMdd'T'HHmmss'.pdf'" ) ;
    String fileName = OffsetDateTime.now( ZoneOffset.UTC ).truncatedTo( ChronoUnit.SECONDS ).format( f )  ;
    

    Use same formatter to parse back to a date-time value.

    OffsetDateTime odt = OffsetDateTime.parse( "Report_20161002T190416Z.pdf" , f ) ;
    

    java.time

    The other Answers are correct but outdated. The troublesome old legacy date-time classes are now supplanted by the java.time classes.

    Get the current moment as an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

    Instant instant = Instant.now();  // 2016-10-02T19:04:16.123456789Z
    

    Truncate fractional second

    You probably want to remove the fractional second.

    Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS );
    

    Or if you for simplicity you may want to truncate to whole minutes if not rapidly creating such files.

    Instant instant = Instant.now().truncatedTo( ChronoUnit.MINUTES );
    

    You can generate a string in standard ISO 8601 format by calling toString.

    String output = instant.toString();
    

    2016-10-02T19:04:16Z

    Stick with UTC

    The Z on the end is short for Zulu and means UTC. As a programmer always, and as a user sometimes, you should think of UTC as the “One True Time” rather than “just another time zone”. You can prevent many problems and errors by sticking with UTC rather than any particular time zone.

    Colons

    Those colons are not allowed in the HFS Plus file system used by Mac OS X (macOS), iOS, watchOS, tvOS, and others including support in Darwin, Linux, Microsoft Windows.

    Use ISO 8601 standard formats

    The ISO 8601 standard provides for “basic” versions with a minimal number of separators along with the more commonly used “extended” format seen above. You can morph that string above to the “basic” version by simply deleting the hyphens and the colons.

    String basic = instant.toString().replace( "-" , "" ).replace( ":" , "" );
    

    20161002T190416Z

    Insert that string into your file name as directed in the other Answers.

    More elegant

    If you find the calls to String::replace clunky, you can use a more elegant approach with more java.time classes.

    The Instant class is a basic building-block class, not meant for fancy formatting. For that, we need the OffsetDateTime class.

    Instant instant = Instant.now().truncatedTo( ChronoUnit.SECONDS );
    OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
    

    Now define and cache a DateTimeFormatter for the “basic” ISO 8601 format.

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" );
    

    Use that formatter instance to generate a String. No more needing to replace characters in the String.

    String output = odt.format( formatter );
    

    You can also use this formatter to parse such strings.

    OffsetDateTime odt = OffsetDateTime.parse( "20161002T190416Z" , formatter );
    

    Zoned

    If you decide to use a particular region’s wall-clock time rather than UTC, apply a time zone in a ZoneId to get a ZonedDateTime object. Similar to an OffsetDateTime but a time zone is an offset-from-UTC plus a set of rules for handling anomalies such as Daylight Saving Time (DST).

    ZoneId z = ZoneId.of( "America/Montreal" );
    ZonedDateTime zdt = instant.atZone( z );
    

    Use the same formatter as above, or customize to your liking.


    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.

提交回复
热议问题