If you wish to use perl to create a date/time stamp, well, there are a few gotchas. We’ll show you one way to navigate the gotchas in this article. See this page for the technical details of the perl localtime function. Interestingly, we will focus on the date format of this very article. 🙂 This also happens to be the default date/time stamp of MySQL. Notice that this format sorts correctly if you just strip out the non-digit characters. Here is a perl script that will create this:
($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst)=localtime(time); printf "%4d-%02d-%02d %02d:%02d:%02d\n", $year+1900,$mon+1,$mday,$hour,$min,$sec;
If we run the script:
# perl time.pl 2003-02-14 16:37:46
The year portion is returned as the number of years since 1900. You also need to add 1 to the month because it starts at 0. The final gotcha is that the localtime function doesn’t pad single digits with another zero. That is why we need to use the printf function with the %02d format option. This will force 4 digits for the year, and 2 digits for the other portions.