PHP strtotime() 函式



定義和用法

strtotime() 函式接受一個日期/時間字串,其中包含文字日期/時間值,並將其解析為 Unix 時間戳。

語法

strtotime($time)

引數

序號 引數和描述
1

time(必填)

此值表示日期/時間字串。

2

now(可選)

這表示一個時間戳,用作相對日期計算的基礎。

返回值

PHP strtotime() 函式返回給定日期字串的時間戳值。如果失敗,此函式將返回布林值 false

PHP 版本

此函式首次引入 PHP 4.0 版,並適用於所有更高版本。

示例

以下示例演示了 strtotime() 函式的用法 -

即時演示
<?php
   $str = strtotime("12 September 2009");
   print("Timestamp: ".$str); 
?>

這將產生以下結果 -

Timestamp: 1252713600

示例

如果將 "now" 作為引數傳遞,則此函式將返回當前時間戳

即時演示
<?php
   $str = strtotime("now");
   print("Timestamp: ".$str); 
?>

這將產生以下結果 -

Timestamp: 1589369948

示例

現在讓我們透過傳遞各種日期值來呼叫此方法 -

即時演示
<?php
   print("Time stamp of 25 December 2019: ".strtotime("25 December 2019")."\n");
   print("Time stamp of +26 day: ".strtotime("+26 day")."\n");
   print("Time stamp of +3 week: ".strtotime("+3 week")."\n");
   print("Time stamp of +3 month 9 days 9 hours: ".strtotime("+3 month 9 days 9 hours")."\n");
   print("Time stamp of last Sunday: ".strtotime("last Sunday")."\n");
   print("Time stamp of next Friday: ".strtotime("next Friday")."\n");
?>

這將產生以下輸出 -

Time stamp of 25 December 2019: 1577232000
Time stamp of +26 day: 1591617718
Time stamp of +3 week: 1591185718
Time stamp of +3 month 9 days 9 hours: 1598130118
Time stamp of last Sunday: 1589068800
Time stamp of next Friday: 1589500800

示例

即時演示
<?php
   $timestamp = strtotime( "February 15, 2015" );   
   print date( 'Y-m-d', $timestamp );
?>

這將產生以下輸出 -

2015-02-15
php_function_reference.htm
廣告