DateTime class does not use locales so here I test and compare its formating with strftime() function's one:
<?php
// Under UNIX, command "$ locale -a" should provide you with your server's options.
$data_do_mysql = "2011-09-29 23:50:26";
echo '<strong>' . "\$data_do_mysql" . '</strong>' . ":" . $data_do_mysql . "." . '<br />' .
'<br />';
$dataInicial = new DateTime(trim($data_do_mysql));
// setlocale() used with strftime().
$meu_locale = setlocale(LC_ALL, "pt_BR.utf8");
$data_inicial = strftime("%d de %b de %Y", strtotime(trim($data_do_mysql)));
// Outputs:
// $data_do_mysql formatada com a classe DateTime:29-Sep-2011.
echo '<strong>' . "\$data_do_mysql" . '</strong>' . " formatada com a classe DateTime:" . $dataInicial->format('d-M-Y') . "." . '<br />' .
'<br />';
// Outputs:
// $data_do_mysql formatada com a função strftime():29 de Set de 2011.
echo '<strong>' . "\$data_do_mysql" . '</strong>' . " formatada com a função strftime():" . $data_inicial . "." . '<br />' .
'<br />';
// setlocale() fails :-(
if (!$meu_locale)
{
echo "Prefiro usar DateTime.";
}
// Yay setlocale() :-D
else
{
echo "Prefiro usar strftime().";
}
exit();
?>
DateTime クラス
(PHP 5 >= 5.2.0)
導入
日付と時刻をあらわします。
クラス概要
DateTime
{
/* 定数 */
/* メソッド */
public static DateTime createFromFormat
( string
}$format
, string $time
[, DateTimeZone $timezone
] )定義済み定数
-
DateTime::ATOMDATE_ATOM - Atom (例: 2005-08-15T15:52:01+00:00)
- HTTP Cookies (例: Monday, 15-Aug-05 15:52:01 UTC)
-
DateTime::ISO8601DATE_ISO8601 - ISO-8601 (例: 2005-08-15T15:52:01+0000)
-
DateTime::RFC822DATE_RFC822 - RFC 822 (例: Mon, 15 Aug 05 15:52:01 +0000)
-
DateTime::RFC850DATE_RFC850 - RFC 850 (例: Monday, 15-Aug-05 15:52:01 UTC)
-
DateTime::RFC1036DATE_RFC1036 - RFC 1036 (例: Mon, 15 Aug 05 15:52:01 +0000)
-
DateTime::RFC1123DATE_RFC1123 - RFC 1123 (例: Mon, 15 Aug 2005 15:52:01 +0000)
-
DateTime::RFC2822DATE_RFC2822 - RFC 2822 (Mon, 15 Aug 2005 15:52:01 +0000)
-
DateTime::RFC3339DATE_RFC3339 -
DATE_ATOMと同じ (PHP 5.1.3 以降) -
DateTime::RSSDATE_RSS - RSS (Mon, 15 Aug 2005 15:52:01 +0000)
-
DateTime::W3CDATE_W3C - World Wide Web Consortium (例: 2005-08-15T15:52:01+00:00)
変更履歴
| バージョン | 説明 |
|---|---|
| 5.2.2 | DateTime オブジェクトどうしの 比較演算子 による比較が、期待通りに動作するようになりました。 これより前のバージョンでは、すべての DateTime オブジェクトは (== による比較で) 等しいと見なされていました。 |
目次
- DateTime::add — 年月日時分秒の値を DateTime オブジェクトに加える
- DateTime::__construct — 新しい DateTime オブジェクトを返す
- DateTime::createFromFormat — 指定した書式でフォーマットした新しい DateTime オブジェクトを返す
- DateTime::diff — ふたつの DateTime オブジェクトの差を返す
- DateTime::format — 指定した書式でフォーマットした日付を返す
- DateTime::getLastErrors — 警告およびエラーを返す
- DateTime::getOffset — タイムゾーンのオフセットを返す
- DateTime::getTimestamp — Unix タイムスタンプを取得する
- DateTime::getTimezone — 指定した DateTime に関連するタイムゾーンを返す
- DateTime::modify — タイムスタンプを変更する
- DateTime::__set_state — __set_state ハンドラ
- DateTime::setDate — 日付を設定する
- DateTime::setISODate — ISO 日付を設定する
- DateTime::setTime — 時刻を設定する
- DateTime::setTimestamp — Unix タイムスタンプを用いて日付と時刻を設定する
- DateTime::setTimezone — DateTime オブジェクトのタイムゾーンを設定する
- DateTime::sub — 年月日時分秒の値を DateTime オブジェクトから引く
- DateTime::__wakeup — __wakeup ハンドラ
marcio dot barbado at bdslabs dot com dot br
22-Mar-2012 07:22
nodweber at gmail dot com
19-Jul-2011 04:22
IF You want to create clone of $time, use clone..
<?php
$now = new DateTime;
$clone = $now; //this doesnot clone so:
$clone->modify( '-1 day' );
echo $now->format( 'd-m-Y' ), "\n", $clone->format( 'd-m-Y' );
echo '----', "\n";
// will print same.. if you want to clone make like this:
$now = new DateTime;
$clone = clone $now;
$clone->modify( '-1 day' );
echo $now->format( 'd-m-Y' ), "\n", $clone->format( 'd-m-Y' );
?>
Results:
18-07-2011
18-07-2011
----
19-07-2011
18-07-2011
giorgio dot liscio at email dot it
14-Aug-2010 12:24
please note that using
setTimezone
setTimestamp
setDate
setTime
etc..
will modify the original object, and the return value is $this
$original = new DateTime("now");
$modified = $original->setTimezone(new DateTimezone("europe/rome"));
echo $original === $modified ? "THE OBJECT IS THE SAME" : "OBJECTS ARE DIFFERENT";
so a datetime object is mutable
bf at tbwb dot nl
10-Aug-2010 05:19
If you have timezone information in the time string you construct the DateTime object with, you cannot add an extra timezone in the constructor. It will ignore the timezone information in the time string:
$date = new DateTime("2010-07-05T06:00:00Z", new DateTimeZone("Europe/Amsterdam"));
will create a DateTime object set to "2010-07-05 06:00:00+0200" (+2 being the TZ offset for Europe/Amsterdam)
To get this done, you will need to set the timezone separately:
$date = new DateTime("2010-07-05T06:00:00Z");
$date->setTimeZone(new DateTimeZone("Europe/Amsterdam");
This will create a DateTime object set to "2010-07-05 08:00:00+0200"
ediathome
20-Mar-2010 02:21
If you need DateTime::createFromFormat functionality in versions <5.3.0 releases you might use the following basic class which can also be combined with Tom's class. It should work for most basic formats, however you should improve this function if you need more complex formats.
<?php
class DateClass extends DateTime{
public function getTimestamp(){
return $this->format ("U");
}
/**
* This function calculates the number of days between the first and the second date. Arguments must be subclasses of DateTime
**/
static function differenceInDays ($firstDate, $secondDate){
$firstDateTimeStamp = $firstDate->format("U");
$secondDateTimeStamp = $secondDate->format("U");
$rv = round ((($firstDateTimeStamp - $secondDateTimeStamp))/86400);
return $rv;
}
/**
* This function returns an object of DateClass from $time in format $format. See date() for possible values for $format
**/
static function createFromFormat ($format, $time){
assert ($format!="");
if($time==""){
return new DateClass();
}
$regexpArray['Y'] = "(?P<Y>19|20\d\d)";
$regexpArray['m'] = "(?P<m>0[1-9]|1[012])";
$regexpArray['d'] = "(?P<d>0[1-9]|[12][0-9]|3[01])";
$regexpArray['-'] = "[-]";
$regexpArray['.'] = "[\. /.]";
$regexpArray[':'] = "[:]";
$regexpArray['space'] = "[\s]";
$regexpArray['H'] = "(?P<H>0[0-9]|1[0-9]|2[0-3])";
$regexpArray['i'] = "(?P<i>[0-5][0-9])";
$regexpArray['s'] = "(?P<s>[0-5][0-9])";
$formatArray = str_split ($format);
$regex = "";
// create the regular expression
foreach($formatArray as $character){
if ($character==" ") $regex = $regex.$regexpArray['space'];
elseif (array_key_exists($character, $regexpArray)) $regex = $regex.$regexpArray[$character];
}
$regex = "/".$regex."/";
// get results for regualar expression
preg_match ($regex, $time, $result);
// create the init string for the new DateTime
$initString = $result['Y']."-".$result['m']."-".$result['d'];
// if no value for hours, minutes and seconds was found add 00:00:00
if (isset($result['H'])) $initString = $initString." ".$result['H'].":".$result['i'].":".$result['s'];
else {$initString = $initString." 00:00:00";}
$newDate = new DateClass ($initString);
return $newDate;
}
}
?>
gmblar+php at gmail dot com
24-Jan-2010 09:53
Small but powerful extension to DateTime
<?php
class Blar_DateTime extends DateTime {
/**
* Return Date in ISO8601 format
*
* @return String
*/
public function __toString() {
return $this->format('Y-m-d H:i');
}
/**
* Return difference between $this and $now
*
* @param Datetime|String $now
* @return DateInterval
*/
public function diff($now = 'NOW') {
if(!($now instanceOf DateTime)) {
$now = new DateTime($now);
}
return parent::diff($now);
}
/**
* Return Age in Years
*
* @param Datetime|String $now
* @return Integer
*/
public function getAge($now = 'NOW') {
return $this->diff($now)->format('%y');
}
}
?>
Usage:
<?php
$birthday = new Blar_DateTime('1879-03-14');
// Example 1
echo $birthday;
// Result: 1879-03-14 00:00
// Example 2
echo '<p>Albert Einstein would now be ', $birthday->getAge(), ' years old.</p>';
// Result: <p>Albert Einstein would now be 130 years old.</p>
// Example 3
echo '<p>Albert Einstein would now be ', $birthday->diff()->format('%y Years, %m Months, %d Days'), ' old.</p>';
// Result: <p>Albert Einstein would now be 130 Years, 10 Months, 10 Days old.</p>
// Example 4
echo '<p>Albert Einstein was on 2010-10-10 ', $birthday->getAge('2010-10-10'), ' years old.</p>';
// Result: <p>Albert Einstein was on 2010-10-10 131 years old.</p>
?>
tom at r dot je
10-Jun-2009 10:00
If you're stuck on a PHP 5.1 system (unfortunately one of my clients is on a rather horrible webhost who claims they cannot upgrade php) you can use this as a quick workaround:
<?php
if (!class_exists('DateTime')) {
class DateTime {
public $date;
public function __construct($date) {
$this->date = strtotime($date);
}
public function setTimeZone($timezone) {
return;
}
private function __getDate() {
return date(DATE_ATOM, $this->date);
}
public function modify($multiplier) {
$this->date = strtotime($this->__getDate() . ' ' . $multiplier);
}
public function format($format) {
return date($format, $this->date);
}
}
}
?>
it is NOT perfect. Timezones and DST are not supported, but if you just need compatible basic functions this works. Feel free to complete this so it's compatible with the 5.2 datetime object.
