Formatted Dates
February 21, 2020
Here is my awk function to return a date-formatted string, which calls the Unix system date
command to do the work (it took several tries to get the quoting right):
function today(fmt, year, month, day, date, str) { if (0 < year + 0 && year + 0 < 10000 && 0 < month + 0 && month + 0 <= 12 && 0 < day + 0 && day + 0 <= 31) { str = "-d \"" month "/" day "/" year "\"" } "date +\"" fmt "\" " str | getline date return date }
Called with just a fmt
parameter, it uses the current date; alternately, the user may specify the date in the three optional parameters. (Yes, awk can handle variadic parameter lists.)
I have to say that I quite enjoy programming with awk, even if it’s very different from Scheme. I also have to say that I don’t feel particularly constrained by using Posix awk rather than Gnu awk; today
is a strong example that most things can be done using either flavor of awk.
You can see the program at https://ideone.com/oI3ky7, but you can’t run it because it shells out to the date
command.
Let’s display the Modified Julian Date. Some C:
@Pascal: nice stuff. Common Lisp formatting is amazing.
Here’s an improved version of my minimal approach that using the Posix clock_gettime function for a more accurate result. Also, I made the format precision a parameter – default is to show microdays, which are slightly less that a tenth of a second: