0

I want to add date to filename just before the file extension.

For example

Input : test.txt or test.png

Output : test-02-Feb-2018_13:05:17-am.txt or test-02-Feb-2018_13:05:17-am.png

Note: anytype not txt only

Stu Dev
  • 13
  • 1
  • 7
  • 1
    Please make a complete sentence and explain what you are trying to do. What are your inputs and expected outputs? What did you try? – jaudo Jan 21 '19 at 14:49
  • i want to upload file i want to add date to filename what ever file type how to add date to filename – Stu Dev Jan 21 '19 at 14:53
  • @StuDev Rather than post clarifications as comments, edit the text of your Question. – Basil Bourque Jan 22 '19 at 03:32
  • Always search Stack Overflow thoroughly before posting. – Basil Bourque Jan 22 '19 at 03:34
  • Tips: Learn about "basic" variations of [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) formats. `OffsetDateTime.now( ZoneOffset.UTC ).format( DateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss'Z'" ) )` – Basil Bourque Jan 22 '19 at 03:36

2 Answers2

0

You should extract base file name and extension from the file, and then reconstruct the file name by adding the date.

This two links should help you :

How do I get the file extension of a file in Java?

How to get the filename without the extension in Java?

I suppose you already know how to format a date

jaudo
  • 2,022
  • 4
  • 28
  • 48
  • You should mark as duplicate or else put relevant details in your answer, not links to other answers. – achAmháin Jan 21 '19 at 15:13
  • This is not a duplicate. By quoting these questions, I give him some clue, without giving the answer which is not the goal here. I added an introduction to my answer to make it more clear. – jaudo Jan 21 '19 at 15:16
0

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

achAmháin
  • 4,176
  • 4
  • 17
  • 40
  • Never use `LocalDateTime` when tracking an actual moment. Lacking any concept of time zone or offset-from-UTC, this class cannot represent a moment, by definition. Use `Instant`, `OffsetDateTime`, or `ZonedDateTime` for a moment. You can get away with using `LocalDateTime` here, but doing so is misleading and confusing. – Basil Bourque Jan 22 '19 at 03:38
  • @BasilBourque good point - it was more to just give an example of how to put something with a timestamp in there but I see where you're coming from. – achAmháin Jan 22 '19 at 15:54