Ever written the occasional Perl script and wanted to insert the current date and time into a MySQL database? Here is the function to do it. This works for a column of type ‘datetime’.
1 2 3 4 5 6 | # function to return the current time in mysql format sub mysql_now() { my($sec,$min,$hour,$mday,$mon,$year,$wday, $yday,$isdst)=localtime(time); my($result)=sprintf("%4d-%02d-%02d %02d:%02d:%02d",$year+1900,$mon+1,$mday,$hour,$min,$sec); return $result; } |
For most datetime formatting needs you should use the POSIX module. If you don’t want to pollute your namespace you can ‘use POSIX ()’ and explicitly call the subroutine. With POSIX, this is generally a good practice anyway.
Also, if you only want to load POSIX when needed you could just require it in the call.
sub mysql_now {
require POSIX;
return POSIX::strftime( ‘%Y-%m-%d %H:%M:%S’, localtime );
}
Link | May 2nd, 2011 at 8:39 pm
HarleyPig: Good to know. I need to check the POSIX module out…:)
Link | May 13th, 2011 at 1:54 pm