Name a file in Java to include date and time stamp

16,211

Solution 1

Use SimpleDateFormat and split to keep file extension:

private static String FILE = "D:\Report.pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE.split(".")[0] + df.format(new Date()) + FILE.split(".")[1];
// filename = "D:\Report20150915152301.pdf"

UPDATE:
if you are able to modify FILE variable, my suggestion will be:

private static String FILE_PATH = "D:\Report";
private static String FILE_EXTENSION = ".pdf";
DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); // add S if you need milliseconds
String filename = FILE_PATH + df.format(new Date()) + "." + FILE_EXTENSION;
// filename = "D:\Report20150915152301.pdf"

Solution 2

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?

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.

Solution 3

You can do something like that

Define your file name pattern as below :

private static final String FILE = "D:\Report_{0}.pdf";
private static final String DATE_PATTERN = "yyyy-MM-dd:HH:mm:ss";

The {0} is a marker to be replaced by the following code

private String formatFileName(Date timeStamp) {
        DateFormat dateFormatter = new SimpleDateFormat(DATE_PATTERN);
        String dateStr = dateFormatter.format(timeStamp);
        return MessageFormat.format(FILE, dateStr); 
}

For further information over date format you can see there and MessageFormat there

Share:
16,211

Related videos on Youtube

Maruthi Srinivas
Author by

Maruthi Srinivas

1) Experience in java application development and testing, functional testing, performance testing, data ware house testing, web services testing and UI testing 2) Hands on experience on Eclipse, Net Beans, quality center, HP-Performance center, HP-Load Runner, JMeter and SOAP-UI 3) Experience in writing SQL queries 4) An exceptional performer with the ability to work in teams as well as excellent communication, analytical, relationship management and problem-solving skills

Updated on September 15, 2022

Comments

  • Maruthi Srinivas
    Maruthi Srinivas over 1 year

    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.

    private static String FILE = "D:\\Report.pdf";
    

    I want to append date and time stamp to the file name generated so that each file created is a unique file. How to achieve this?

  • Marged
    Marged over 8 years
    just a suggestion: as you are no longer able to use FILE directly in the codeyou could use D:\Report_%s.pdf and then String.format. Would save you from splitting
  • Jordi Castilla
    Jordi Castilla over 8 years
    In this situation, I would'n use FILE instead, i would create a better way to construct filename. but as long as is the only OP clue we have in the question.... I think is mandatory to use it xD
  • Maruthi Srinivas
    Maruthi Srinivas over 8 years
    date is coming after extension. See the file name created: Report.pdf20150915065305
  • Jordi Castilla
    Jordi Castilla over 8 years
    @MaruthiSrinivas have you checked my last update using split(".")??
  • Maruthi Srinivas
    Maruthi Srinivas over 8 years
    I am using the following code to generate the file. private static String FILE = "D:\\Report.pdf"; DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss"); String filename = FILE + df.format(new Date()); Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(filename));
  • Jordi Castilla
    Jordi Castilla over 8 years
    you are using wrong code, please, check the updates in my answer, also, don't paste code in comments, it's really dificult to read
  • Maruthi Srinivas
    Maruthi Srinivas over 8 years
    Thank You @Jordi Castilla. Your code worked for me. Thank you very much. My problem is solved
  • Olivier Cailloux
    Olivier Cailloux over 4 years
    Even more elegant (IMHO): let the formatter take care of the time zone rather than using an OffsetDateTime (inappropriate here as we in fact do not care about the time zone).