strtotime()函數(shù)將任何字符串的日期時(shí)間描述解析為 Unix 時(shí)間戳
strtotime()函數(shù)函數(shù)接受帶有文本日期/時(shí)間值的日期/時(shí)間字符串,并將其解析為Unix時(shí)間戳。
注意:如果年份表示使用兩位數(shù)格式,則值 0-69 會(huì)映射為 2000-2069,值 70-100 會(huì)映射為 1970-2000。
注意:請注意 m/d/y 或 d-m-y 格式的日期,如果分隔符是斜線(/),則使用美洲的 m/d/y 格式。如果分隔符是橫杠(-)或者點(diǎn)(.),則使用歐洲的 d-m-y 格式。為了避免潛在的錯(cuò)誤,您應(yīng)該盡可能使用 YYYY-MM-DD 格式或者使用 date_create_from_format() 函數(shù)。
strtotime($time)
序號(hào) | 參數(shù)及說明 |
---|---|
1 | time(必需) 此值表示日期/時(shí)間字符串。 |
2 | now(可選) 這表示一個(gè)時(shí)間戳,用作計(jì)算相對日期的基礎(chǔ)。 |
PHP strtotime()函數(shù)返回給定日期字符串的時(shí)間戳值。如果失敗,此函數(shù)將返回布爾值false。
此函數(shù)最初是在PHP 4.0版中引入的,并且可以在所有更高版本中使用。
PHP 5.3.0:現(xiàn)在相對時(shí)間格式,比如這一周、前一周、上一周、下一周,指定一周從星期一到星期日,而不是使用相對于當(dāng)前日期/時(shí)間的前后 7 天。
PHP 5.3.0: 現(xiàn)在 24:00 是有效的格式。
PHP 5.2.7:在這更早版本中,如果請求一個(gè)月中某個(gè)給定日期且該日期剛好是該月的第一天,則會(huì)錯(cuò)誤地把增加一個(gè)星期到返回的時(shí)間戳中,這點(diǎn)現(xiàn)在已經(jīng)得到更正。
PHP 5.1.0:如果失敗則返回 FALSE(在這更早版本則返回 -1),并增加了 E_STRICT 和 E_NOTICE 時(shí)區(qū)錯(cuò)誤。
PHP 5.0.2:現(xiàn)在正確計(jì)算 "now" 和其他相對時(shí)間是以當(dāng)前時(shí)間為準(zhǔn),而不是以今天午夜的時(shí)間為準(zhǔn)。
PHP 5.0.0:允許微秒(但微秒數(shù)通常被忽略)。
以下示例演示了strtotime()函數(shù)的用法-
<?php $str = strtotime("12 September 2009"); print("Timestamp: ".$str); ?>測試看看?/?
輸出結(jié)果
Timestamp: 1252713600
如果傳遞“ now”作為參數(shù),則此函數(shù)返回當(dāng)前時(shí)間戳
<?php $str = strtotime("now"); print("Timestamp: ".$str); ?>測試看看?/?
輸出結(jié)果
Timestamp: 1589369948
現(xiàn)在,讓我們通過傳遞各種日期值來調(diào)用此方法-
<?php // 設(shè)置時(shí)區(qū) date_default_timezone_set("PRC"); $time = strtotime("2020-01-18 08:08:08"); // 將指定日期轉(zhuǎn)成時(shí)間戳 // 打印當(dāng)前時(shí)間 PHP_EOL 換行符,兼容不同系統(tǒng) echo $time, PHP_EOL; // 更多實(shí)例 echo strtotime("now"), PHP_EOL; echo strtotime("now"), PHP_EOL; echo strtotime("10 September 2019"), PHP_EOL; echo strtotime("+1 day"), PHP_EOL; echo strtotime("+1 week"), PHP_EOL; echo strtotime("+1 week 2 days 4 hours 2 seconds"), PHP_EOL; echo strtotime("next Thursday"), PHP_EOL; echo strtotime("last Monday"), PHP_EOL; ?>測試看看?/?
這將產(chǎn)生以下輸出-
1579306088 1596165501 1596165501 1568044800 1596251901 1596770301 1596957503 1596643200 1595779200
格式化為YYYY-MM-DD,并輸出日期
<?php $timestamp = strtotime( "February 15, 2015" ); print date( 'Y-m-d', $timestamp ); ?>測試看看?/?
這將產(chǎn)生以下輸出-
2015-02-15