Name a File in Java to Include Date and Time Stamp

Current timestamp as filename in Java

No need to get too complicated, try this one liner:

String fileName = new SimpleDateFormat("yyyyMMddHHmm'.txt'").format(new Date());

Name a file in Java to include date and time stamp

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"

timestamp as file name in java

If you are on Windows your file name cannot contain :, you need to replace it by another character...

The following characters are reserved :

< (less than)
> (greater than)
: (colon)
" (double quote)
/ (forward slash)
\ (backslash)
| (vertical bar or pipe)
? (question mark)
* (asterisk)

For example :

String yourTimeStamp = "01-01-2016 17:00:00";
File yourFile = new File("your directory", yourTimeStamp.replace(":", "_"));

Creating a text file with the current date and time as the file name in Java

Guessing: either

  1. your operating system doesn't allow to use the / character in file names
  2. or it thinks that / separates directories; in other words: you are trying to create a file in a subdirectory ... that probably doesn't exist

And unrelated, but important too: you should not mix such things. You should put the code that creates and writes that file into its own utility class; instead of pushing it into your UI related code.

You see, if you had created a helper class here; it would also be much easier to do some unit-testing on that one; to ensure it does what you expect it to do.

Add date to my file name before any extension

The easiest option is (assuming you always have an extension) is to get the last index of . and use String::substring to get the parts of the filename you need, and insert the timestamp of choice.

For example, something you could use and manipulate to your liking:

String filename = "test.txt";
System.out.println(filename.substring(0, filename.lastIndexOf(".")) + LocalDateTime.now() + filename.substring(filename.lastIndexOf(".")));

Output:

test2019-01-21T15:20:34.992.txt



Related Topics



Leave a reply



Submit