note 61944 deleted from function.date by derick

From: Date: Sun, 11 Jun 2006 11:43:40 +0000
Subject: note 61944 deleted from function.date by derick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-114252@lists.php.net to get a copy of this message
Note Submitter: Kyle M. Hall ---- I need a way to create mysql timestamps from the past at certain invervals (ie 30 days ago, 14 days ago). This is a painfully bad class to give you a mysql timestamp or date string for a day in the past. It won't work for a time further back than last month. If someone could turn this into something useful that would be great. <?php class Calendar{ protected $year; protected $month; protected $day; protected $hour = '00'; protected $minute = '00'; protected $second = '00'; protected $daysOfMonth = array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); protected $daysOfMonthLY = array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); function __construct(){ //could be overloaded so that we could use a date in the past or future instead of current date. $today = getdate(); $this->year = $today['year']; $this->month = $today['mon']; $this->day = $today['mday']; } // Checks to see if the current year is a leap year protected function isLeapYear($year) { if (($year/4) != floor($year/4)) return false; if (($year/100) != floor($year/100)) return true; if (($year/400) != floor($year/400)) return false; return true; } public function getDateXDaysAgo($days, $format){ // If days is less than the current day, it is within the same month and we can simply subtract it. if($days < $this->day){ $day = $this->day - $days; if ($this->month < 10) {$month = '0' . $this->month;} else {$month = $this->month;} if ($day < 10) {$day = '0' . $day;} $timestamp = $this->year . $month . $day . $this->hour . $this->minute . $this->second; } else { if($this->month == '01'){//We will be switching to a different year $year = $this->year - 1; $month = 12; $days -= $this->day; $day = 31 - $days; if ($month < 10) {$month = '0' . $month;} $timestamp = $year . $month . $day . '00' . '00' . '00'; } else { //Not switching year, just switching month. $year = $this->year; $months = Calendar::isLeapYear($year) ? $this->daysOfMonthLY : $this->daysOfMonth; $month = $this->month - 1; $days -= $this->day; $day = $months[$month - 1] - $days; if ($month < 10) {$month = '0' . $month;} $timestamp = $year . $month . $day . '00' . '00' . '00'; } } switch($format){ case "Timestamp": return $timestamp; break; //Seems superflous, doesn't it : ) case "String": return date('l dS \of F Y', Calendar::mysqlToUnixTimestamp($timestamp)); break; } } protected function mysqlToUnixTimestamp($mysql_timestamp){ preg_match('/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/', $mysql_timestamp,$pieces); $unix_timestamp = mktime($pieces[4], $pieces[5], $pieces[6], $pieces[2], $pieces[3], $pieces[1]); return($unix_timestamp); } } ?>

« previous php.notes (#114252) next »