Format date and time as you like most
Jump to navigation
Jump to search
Problem. How do I make a string containing the current date and time with a format I like ?
Solution. Just follow this example. I use Printf package here because it lets me state I want in output an integer printed with 2 digits padding it with zeroes if necessary.
Feature require: 'Printf'
# make a DataAndTime object with the current date and time, then we print it the way we want
d0 _ DateAndTime now.
# a very much standard date printing for e.g. a log file
'myFile-%d-%02d-%02d-%02d-%02d.log' printf: {
d0 yearNumber. d0 monthIndex. d0 dayOfMonth. d0 hour24. d0 minute }
" 'myFile-2021-09-06-10-04.log' "
# a more personal date format, fit for human eyes
'%s-%02d-%s-%d-%02d:%02d' printf: {
d0 dayOfWeekAbbreviation. d0 dayOfMonth. d0 monthAbbreviation .
d0 yearNumber . d0 hour24. d0 minute }
"=> 'Mon-06-Sep-2021-10:04' "
Exercise. In the second example put the full month name, use the Browser to discover the proper message name.
Exercise. Get in output the current time in 12h format, that e.g. '10:00 AM'.
Exercise. Try to use String>>format: instead of String:printf: and see what happens.