- <?php
- echo date("Y-m-d H:i:s", "1364800128");
- echo "<br />";
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8" />
- <title>Getting started with dates in php5</title>
- </head>
- <body>
- <?php
- date_default_timezone_set('Asia/Shanghai');
- echo "Today is ",date('l');
- echo "<br />";
- ?>
- <!--如果你看了php手冊中PHP date function,那麼你將發現有很多格式化日期的方式。-->
- <?php
- echo "Today is ",date('Y-m-d');
- echo "<br />";
- ?>
- <!--將得到:Today is 2012-08-17-->
- <!--有一些日期是很普遍地被使用,所以PHP提供了一些常量供你使用。舉例,你可以使用Cookie獲取到客戶端日期。-->
- <?php
- echo "Today is ",date(DATE_COOKIE);
- echo "<br />";
- ?>
- <!--你將得到如下面的內容:Today is Friday, 17-Aug-12 11:34:38 CST-->
- <!--注意當使用常量的時候不要使用引號。-->
- <!--如果你想要輸出當前時間,你能使用date(不同格式化字符參數)。-->
- <?php
- echo "The time is ",date('g:i:sa');
- echo "<br />";
- ?>
- <!--你將得到:The time is 11:39:59am-->
- <!--PHP在解釋字符方面是相當靈巧的,但不是完美的,因此,在你插入之前一定要測試你輸入的字符。使用"english-like instructions"轉化成需要的時間戳,這是一個非常不錯的方式。你可以像下面這樣做:
- -->
- <?php
- $nextfriday=strtotime("next Friday"); //下週五
- $nextmonth=strtotime("+1 Month"); //從今天開始計算一個月以後的時間
- $lastchristmas=strtotime("-1 year dec 25"); //去年聖誕節
- echo $nextfriday;
- echo "<br />";
- echo $nextmonth;
- echo "<br />";
- echo $lastchristmas;
- echo "<br />";
- ?>
- <!--
- 獲取日期範圍
- strtotime返回的值被轉換爲數字,我們能夠用這些數字做基礎運算,我們可以用這些數字做很多非常有意思的事情。比如,你每週二需要教一門功課,爲期16周,你想得到你教科時間。你能夠做下面的事情。-->
- <?php
- $startdate = strtotime('next Tuesday');
- $enddate = strtotime('+16 weeks', $startdate);
- $currentdate = $startdate;
- echo '<ol>';
- while($currentdate < $enddate):
- echo "\t<li>", date('M d', $currentdate);
- $currentdate = strtotime('+1 week', $currentdate);
- endwhile;
- echo '</ol>';
- echo "<br />";
- ?>
- <!--
- 你將會得到如下的結果:
- Aug 21
- Aug 28
- Sep 04
- Sep 11
- Sep 18
- Sep 25
- Oct 02
- Oct 09
- Oct 16
- Oct 23
- Oct 30
- Nov 06
- Nov 13
- Nov 20
- Nov 27
- Dec 04
- 注意一下這行:$currentdate = strtotime("+1 week", $currentdate)。在這行,你會發現你需要指定一個時間戳做爲第二個參數,strtotime將使用這個參數代替默認時間戳(今天),並進行運算。
- -->
- <!--
- 到某一個日期的天數
- 使用計算器的時候,我們會試圖去計算到某一天的天數。你很容易計算11月份第四個星期四的時間戳。
- -->
- <?php
- $someday = strtotime("3 weeks thursday November 1");
- $daysUtilDate = ceil(($someday - time())/60/60/24);
- echo "There are ", $daysUtilDate, " until Thanksgiving";
- ?>
- <!--
- 首先,我們開始計算感恩節日期(11月1號之後的第一個星期四之後的第3個星期四),然後我們通過簡單的算術,計算出感恩節到當前時間之間的天數。當我們進行比較運算的時候,我們可以使用time(),因爲它返回,到當前時間的紀元秒數。
- -->
- </body>
- </html>