C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
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
And: It has a prefix ("file") and an extension "txt." We can write a file with this name to a directory.