Producing MySQL dates from Perl

April 24, 2011

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;
}

tags: , , , , , , ,
posted in Computing by Mark Veltzer

Follow comments via the RSS Feed | Leave a comment | Trackback URL

2 Comments to "Producing MySQL dates from Perl"

  1. HarleyPig wrote:

    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 );
    }

  2. Mark Veltzer wrote:

    HarleyPig: Good to know. I need to check the POSIX module out…:)

Leave Your Comment

 
Powered by Wordpress and MySQL. Theme by Mark Veltzer derived from Shlomi Noachs openark theme