Home
Java
Filename With Date Example (Format String)
This page was last reviewed on Feb 23, 2023.
Dot Net Perls
Filename, Dates. A program generates a file on a regular time schedule. We can use the current date and time as a filename. This avoids file system conflicts.
String.format. With a format string, we create a filename String. We specify that the year, month, day, hour, minute and second is present.
Example program. This program first calls Calendar.getInstance to access a calendar. It then sets the time to the current instant—it uses the now() method.
Start We invoke the String.format method with two arguments: a format string, and the calendar containing the current date.
Note We use the "Ymd" chars for the year, month and the day. We use "kSp" for the hour, seconds and the "pm" string.
Tip To format a value as a time, we prefix our code with the lowercase letter "t." The "%1" part indicates the argument position.
import java.time.Instant; import java.util.Calendar; import java.util.Date; public class Program { public static void main(String[] args) { // Get a Calendar and set it to the current time. Calendar cal = Calendar.getInstance(); cal.setTime(Date.from(Instant.now())); // Create a filename from a format string. // ... Apply date formatting codes. String result = String.format( "file-%1$tY-%1$tm-%1$td-%1$tk-%1$tS-%1$tp.txt", cal); // Display our result filename. System.out.println("Filename:"); System.out.println(result); } }
Filename: file-2015-05-04-16-07-pm.txt
Program result. The program generated a string with a filename that could be used to store time-sensitive information. It contains the date, month, year, hour, minute and seconds.
And It has a prefix ("file") and an extension "txt." We can write a file with this name to a directory.
Format strings are concise. With the format string in this example we can add six time fields to a filename in one line of code. The symbols are hard to read, but can be learned.
For log files, or files that are written on a timed basis, this approach to generating filenames is useful. It avoids conflicts which could caused at a loss.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Feb 23, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.