Home > php教程 > php手册 > body text

PHP日期格式转时间戳

WBOY
Release: 2016-06-13 09:39:03
Original
951 people have browsed it

PHP 提供了函数可以方便的将各种形式的日期转换为时间戳,该类函数主要是:

  • strtotime():将任何英文文本的日期时间描述解析为时间戳。
  • mktime():从日期取得时间戳。

strtotime()

strtotime() 函数用于将英文文本字符串表示的日期转换为时间戳,为 date() 的反函数,成功返回时间戳,否则返回 FALSE 。语法:

int strtotime ( string time [, int now] )
Copy after login

参数 time 为被解析的字符串,是根据 GNU 日期输入格式表示的日期。

例子:

<?php
echo strtotime("2009-10-21 16:00:10");	//输出 1256112010
echo strtotime("10 September 2008");	//输出 1220976000
echo strtotime("+1 day"), "<br />";	//输出明天此时的时间戳
?>
Copy after login

mktime()

mktime() 函数用于从日期取得时间戳,成功返回时间戳,否则返回 FALSE 。语法:

int mktime(时, 分, 秒, 月, 日, 年)
Copy after login

例子:

<?php
echo mktime(21, 50, 55, 07, 14, 2010);		//输出“1279115455”
?>
Copy after login

参数可以从右向左省略,任何省略的参数会被设置成本地日期和时间的当前值。

mktime() 在做日期计算和验证方面很有用,它会自动计算超出范围的输入的正确值。例如下面例子输出的都是 2008-01-01:

<?php
echo date("Y-m-d", mktime(0, 0, 0, 12, 32, 2007));
echo date("Y-m-d", mktime(0, 0, 0, 13, 1, 2007));
?>
Copy after login

下个月的最后一天。任何给定月份的最后一天都可以被表示为下个月的第 "0" 天,而不是 -1 天,如下面的例子:

<?php
$lastday = mktime(0, 0, 0, 3, 0, 2008);
echo strftime("2008年最后一天是:%d", $lastday);
// 2008年最后一天是:29
?>
Copy after login

自定义函数

下面的函数与strtotime功能差不多。

<?php
$date_str = "2011-09-11 17:00:00";
echo $time_str = str_format_time($date_str);

function str_format_time($timestamp = '')
{   
	if (preg_match("/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} (0[0-9]|1[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])/i", $timestamp)) 
	{
		list($date,$time)=explode(" ",$timestamp);
		list($year,$month,$day)=explode("-",$date);
    	list($hour,$minute,$seconds )=explode(":",$time);
 		$timestamp=gmmktime($hour,$minute,$seconds,$month,$day,$year);
	}
	else
	{
		$timestamp=time();
	}
	return $timestamp;
}

echo '<br />';
echo date("Y-m-d H:i:s", $time_str);

?>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!