Java Filename With Date Example (Format String)

Use a format string to create a filename based on the current date and time. Use Calendar and String.format.
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.Format
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.

String.format: We invoke the String.format method with two arguments: a format string, and the calendar containing the current date.

Format string: We use the "Ymd" chars for the year, month and the day. We use "kSp" for the hour, seconds and the "pm" string.

Time: To format a value as a time, we prefix our code with the lowercase letter "t." The "%1" part indicates the argument position.

Java program that uses filename, Date, Calendar 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); } } Output 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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls