note 39055 added to function.date

From: Date: Thu, 15 Jan 2004 15:46:49 +0000
Subject: note 39055 added to function.date
Groups: php.notes 
Request: Send a blank email to php-notes+get-63625@lists.php.net to get a copy of this message
This similar function is similar to date(), but is can accept $date in several different formats. Some simple regex's help create the timestamps, then the date is returned in $format. $format can be a string in $date_formats, or anything you would normally pass to date(). I use this to convert dates easily between MySQL date format, UNIX timestamp or a date format the user understands - without needing to use mktime(). <?php function format_date($date = time(), $format = 'timestamp') { // Valid return values... $date_formats = array('mysql_date' => 'Y-m-d', 'mysql_time' => 'H:i:s', 'mysql_datetime' => 'Y-m-d H:i:s', 'timestamp' => 'U', 'short' => 'd/m/Y', 'long' => 'jS F, Y', 'formatted' => 'r'); if (isset($date_formats[$format])) { $format = $date_formats[$format]; } if (preg_match("#^(\d{9,11})$#", $date)) { $timestamp = $date; } else if (preg_match("#^(\d{4}\-\d{2}-\d{2})$#", $date)) { list($year, $month, $day) = explode("-", $date); $timestamp = mktime(0, 0, 0, $month, $day, $year); } else if (preg_match("#^(\d{4}\-\d{2}-\d{2}\s\d{2}\:\d{2}:\d{2})$#", $date)) { list($date_part, $time_part) = explode(" ", $date); list($year, $month, $day) = explode("-", $date_part); list($hour, $minute, $second) = explode(":", $time_part); $timestamp = mktime($hour, $minute, $second, $month, $day, $year); } else if (preg_match("#^(\d{2}/\d{2}/\d{4})$#", $date)) { list($day, $month, $year) = explode("/", $date); $timestamp = mktime(0, 0, 0, $month, $day, $year); } else { die ("Incorrect date format: $date "); } $formatted_date = date($format, $timestamp); return $formatted_date; } ?> It works for me! Steve. ---- Manual Page -- http://www.php.net/manual/en/function.date.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39055 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39055&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39055&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#63625) next »