Управление различиями в форматах даты между PHP и MySQL

Я пишу свое первое приложение PHP, которое должно напрямую заниматься датами, и, таким образом, напрямую иметь дело с тем, что PHP и MySQL имеют разные форматы дат.

Мой вопрос: какой самый элегантный способ справиться с этим различием?

У меня есть следующие две функции для управления разницей с помощью php:

function mysql_date($php_date) { return date( 'Ymd H:i:s', $php_date ); } function php_date($mysql_date) { $val = explode(" ",$mysql_date); $date = explode("-",$val[0]); $time = explode(":",$val[1]); return mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]); } 

есть ли более простой способ управлять этим непосредственно в моих SQL-запросах?

Или вы могли бы предложить любой другой более элегантный способ справиться с этим?

Поскольку (вокруг) PHP 5.2, PHP имеет встроенный класс / объект для работы с датами и временем, называемый DateTime . В пустоте всегда лучше использовать встроенную систему, чем бороться с беспорядочными деталями.

Конструктор DateTime (или функция date_create) принимает дату в любом формате, понятном strToTime. Все, что вам нужно знать о strToTime – это волшебное вуду, которое будет правильно распознавать дату почти в любом строчном формате. Когда я впервые столкнулся с strToTime, у меня была такая же внутренняя реакция, что и сейчас («это фигня / кажется ненадежной»). Это не. Это просто работает таким образом, что ваше собственное хрупкое понимание дат никогда не будет (и если вы считаете, что понимаете даты, вы этого не делаете. Поверьте мне.)

Итак, вытащите информацию из MySQL в виде строки Date / Time и сразу создайте PHP Date Object. Используйте метод date_format (с некоторыми удобными константами ), когда / если вам нужна дата снова в виде строки.

Вы можете заменить php_date на strtotime .

 $php = strtotime($mysql); 

Эквивалентом MySQL будет UNIX_TIMESTAMP .

Хотя, если вы хотите обрабатывать форматирование в SQL, попробуйте DATE_FORMAT MySQL.

Храните все в базе данных в поле даты и времени в формате UTC. Для манипуляции с PHP используйте библиотеку Date PEAR . Я не большой пользователь PEAR, но эта библиотека фантастична и будет обрабатывать все неприятные проблемы с преобразованием даты, которые вы не должны тратить свое время на беспокойство.

Я бы порекомендовал вам хранить все в формате mysql, пока вам не нужно отобразить его для пользователя, а затем используйте strtotime (), чтобы получить временную метку unix и дату () для ее форматирования.

Если вы введете венгерскую нотацию, еще труднее пойти не так:

 $ymdDateAdded = date('Ym-d'); $timeDateAdded = strtotime($ymdDateAdded); $userDateadded = date('j F Y', $timeDateAdded); 

Я думаю, что было бы лучше идеей хранить временные метки unix в поле БД. Когда вам нужно отображать даты на человеческом языке, вы всегда можете использовать функцию date () php. Для всего остального просто используйте цифровую метку времени.

Вы можете создать небольшой объект даты, который просто преобразует дату так, как вам нужно.

 $Date_p = new MagicDate($php_date); $Date_m = new MagicDate($mysql_date); 

$Date_p и $Date_m просто показывают, что вы можете посеять объект так или иначе, как вам нужно. Если вам нужна дата mysql, у вас будет код. Реально это было бы что-то довольно общее, как $Date .

 $query = "UPDATE SET Date='".$Date_p->toMysql()."' "... 

и наоборот, когда вам нужно обратное. Вы можете использовать уже созданные функции. Просто добавьте «сниффер» в метод построения, например:

 public function __construct($date) { $phpdate = strtotime($date); if($phpdate) { $this->phpdate = $phpdate; $this->mysqldate = $this->mysql_date($phpdate); } else { $this->phpdate = $this->php_date($phpdate); $this->mysqldate = $phpdate; } } 

Бросьте некоторые ошибки обработки, чтобы поймать вещи, которые идут плохо. Добавьте получателя для двух дат. И это набор и забыть об этом. Просто вытащите правильную дату, когда вам это нужно.

Могут быть некоторые оптимизации, но это просто покажет вам, как это может работать.

Это лучший способ сэкономить время и дату как временную метку unix, а не другие форматы.

Я создал класс для обработки даты и времени в php. Его простой в использовании и очень полезный

 <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> с <?php define("NEW_LINE", "</BR>"); class scTimestamp { private $timestamp; private $year; private $month; private $day; private $hour; private $minute; private $second; public function __construct() { register_shutdown_function(array($this,'__destruct')); $this->setTimestamp($_SERVER['REQUEST_TIME']); } public function __destruct() { unset($this->timestamp); unset($this->year); unset($this->month); unset($this->day); unset($this->hour); unset($this->minute); unset($this->second); } private function rebuildTimestampFromDate() { $this->timestamp=mktime($this->hour,$this->minute,$this->second,$this->month,$this->day,$this->year); } private function rebuildDateFromTimestamp() { $this->day=date('j',$this->timestamp); $this->month=date('n',$this->timestamp); $this->year=date('Y',$this->timestamp); $this->hour=date('g',$this->timestamp); $this->minute=date('G',$this->timestamp); $this->second=date('s',$this->timestamp); } public function setTimestamp($tempTimestamp) { $this->timestamp=$tempTimestamp; $this->rebuildDateFromTimestamp(); } public function getTimestamp() { return $this->timestamp; } public function setYear($tempYear) { $this->year = $tempYear; $this->rebuildTimestampFromDate(); } public function getYear() { return $this->year; } public function setMonth($tempMonth) { $this->month = $tempMonth; $this->rebuildTimestampFromDate(); } public function getMonth() { return $this->month; } public function setDay($tempDay) { $this->day=$tempDay; $this->rebuildTimestampFromDate(); } public function getDay() { return $this->day; } public function setHour($tempHour) { $this->hour = $tempHour; $this->rebuildTimestampFromDate(); } public function getHour() { return $this->hour; } public function setMinute($tempMinute) { $this->minute = $tempMinute; $this->rebuildTimestampFromDate(); } public function getMinute() { return $this->minute; } public function setSecond($tempSecond) { $this->second = $tempSecond; $this->rebuildTimestampFromDate(); } public function getSecond() { return $this->second; } public function getDateDifferenceFromNow() { return $this->getDateDifferenceFrom($_SERVER['REQUEST_TIME']); } public function getDateDifferenceFrom($fromDate) { $return=""; $sec=" Second"; $min=" Minute"; $hrs=" Hour"; $before=" Before"; $difference=$fromDate-$this->getTimestamp(); if($difference<0) $return.="In the Future"; else if($difference<60) { if($difference>1) $sec.="s"; $return.= $difference.$sec.$before; } else if($difference<3600) { $difference=intval($difference/60); if($difference>1) $min.="s"; $return.=$difference.$min.$before; } else if($difference<86400) { $difference=intval($difference/3600); if($difference>1) $hrs.="s"; $return= $difference.$hrs.$before; } else if($difference<604800) { $return.= date("lg:ia",$this->getTimestamp()); } else if($difference<28512000) { $return.= date("F j",$this->getTimestamp()); } else { $return.= date("F j, Y, g:ia",$this->getTimestamp()); } return $return; } public function getDateAsString() { return date("F j, Y",$this->getTimestamp()); } public function getDateTimeAsString() { return date("F j, Y, g:ia",$this->getTimestamp()); } public function __toString() { $return = NEW_LINE."^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; $return.= NEW_LINE."@@ Timestamp: ".$this->getTimestamp()." @@".NEW_LINE; $return.= NEW_LINE."@@ Date: ".$this->getDateTimeAsString()." @@".NEW_LINE; $return.= NEW_LINE." ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^".NEW_LINE; return $return; } } ?> 

как только он включен, его можно использовать как

 include_once("scTimestamp.php"); $test=new scTimestamp(); echo $test->getDateAsString(); $test->setTimestamp(1210203200); echo $test->getDateDifferenceFromNow(); echo $test; $test->setTimestamp(121020320022); echo $test->getYear(); echo $test; 

И результат понравится.

26 июня 2015 года 7 мая 2008 года, 11:33 вечера ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^ @@ Временная метка: 1210203200 @@ @@ Дата: 7 мая 2008 г., 11:33 вечера @@ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^. : 25 декабря, 5804, 3:33 утра @@ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Этот класс можно использовать в соответствии с потребностями