We Recommend

Learning Perl Learning Perl
In this smooth, carefully paced course, a leading Perl trainer teaches you to program in the language that threatens to make C, sed, awk, and the Unix shell obsolete for many tasks. This book is the "official" guide for both formal (classroom) and informal learning. It is fully accessible to the novice programmer.


Posted By

eszpee on 02/14/08


Tagged

mysql db date


Versions (?)


Date functions


Published in: Perl 


  1. sub date_mysql2sec {
  2. #takes: date in "yyyy-mm-dd hh:mm:ss" format (with some freedom)
  3. #returns: date in seconds since 1970 format
  4. use Time::Local;# 'timelocal_nocheck';
  5. my $mysqldate = shift;
  6. $mysqldate =~ /(\d{4}).(\d{2}).(\d{2}).(\d{2}).(\d{2}).(\d{2})/;
  7. my ($sec,$min,$hour,$mday,$mon,$year) = ($6,$5,$4,$3,$2,$1);
  8. if ($mon != 0) {$mon--};
  9. return timelocal($sec,$min,$hour,$mday,$mon,$year);
  10. }
  11.  
  12. sub date_sec2mysql {
  13. #takes: date in seconds since 1970 format
  14. #returns: date in yyyy-mm-dd hh:mm:ss format
  15. my $secdate = shift;
  16. my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday) = localtime($secdate);
  17. $year += 1900;
  18. $mon++;
  19. $mon = $mon < 10 ? "0$mon" : $mon;
  20. $mday = $mday < 10 ? "0$mday" : $mday;
  21. $sec = $sec < 10 ? "0$sec" : $sec;
  22. $min = $min < 10 ? "0$min" : $min;
  23. $hour = $hour < 10 ? "0$hour" : $hour;
  24. return qq{$year-$mon-$mday $hour:$min:$sec};
  25. }
  26.  
  27. sub date_mysql_now {
  28. #Takes: nothing
  29. #Returns: current date and time in yyyy-mm-dd hh:mm:ss format
  30. return date_sec2mysql(time);
  31. }

Report this snippet 

You need to login to post a comment.