PHP: Basic Date/Time Functions


/ Published in: PHP
Save to your folder(s)

Dates and Time are always important to understand in any language. PHP has some rockin' functions but here are a few that I use the most.


Copy this code and paste it in your HTML
  1. function strip_zeros_from_date( $marked_string = "" ){
  2. //Remove any Zeros in the date
  3. $no_zeros = str_replace('*0', '', $marked_string );
  4. //Remove the Asterik regardless of no Zeros
  5. $cleaned_string = str_replace('*', '', $no_zeros );
  6.  
  7. return $cleaned_string;
  8. }
  9.  
  10. //Number of seconds since January 1, 1970
  11. echo $time = time();
  12. echo "<br /><br />";
  13.  
  14. //Make a timestamp using mktime( $hr, $min, $sec, $mo, $day, $yr )
  15. echo $mktime = mktime( 2, 30, 45, 10, 1, 2009 );
  16. echo "<br /><br />";
  17.  
  18. //Convert this date to a string
  19. echo $date = strtotime("September 15, 2000");
  20. echo "<br /><br />";
  21.  
  22. //Convert Last Monday to a String
  23. echo $last_monday = strtotime("last Monday");
  24. echo "<br /><br />";
  25.  
  26. //Convert 1 day from today to a String
  27. echo $tomorrow = strtotime("+1 day");
  28. echo "<br /><br />";
  29.  
  30. //Check if this date is valid (February 31st)
  31. echo $valid_date = checkdate( 2, 31, 2000 ) ? "true" : "false";
  32. echo "<br /><br />";
  33.  
  34. //Format a Unix Timestamp into something human readable (http://php.net/manual/en/function.strftime.php)
  35. //The asterik is neat little hack that will help us build a helper function
  36. echo strip_zeros_from_date( strftime( "*%m/*%d/%y", $last_monday ) );
  37.  
  38. echo "<br /><br />";
  39.  
  40. //Format your date in PHP for MySQL
  41. $dt = time();
  42. $mysql_datetime = strftime("%Y-%m-%d %H:%M:%S", $dt);
  43. echo $mysql_datetime;

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.