首页 编程语言 php

每天PHP函数:time、date、strtotime、microtime函数

strtotime()函数

将任何英文文本的日期或时间描述解析为 Unix 时间戳

用法:strtotime($time,$now);

第一个参数:规定日期/时间字符串。

第二个参数:可选。规定用来计算返回值的时间戳。如果省略该参数,则使用当前时间。

用例:

<?php
	header("Content-Type: text/html;charset=utf-8");
	date_default_timezone_set('PRC');
	$time = time();//当前时间的时间戳
	echo strtotime(now);//1548831887(当前时间的时间戳)
	echo strtotime("-1 month");//距当前时间一个月时间戳1546154020
	echo date('Y-m-d H:i:s',strtotime("-1 month"));
 //2018-12-30 15:11:46(距当前时间一个月)
?>

time()函数

函数返回自 Unix 纪元(January 1 1970 00:00:00 GMT)起的当前时间的秒数。

用法:time();

用例:

<?php
	header("Content-Type: text/html;charset=utf-8");
	date_default_timezone_set('PRC');
	echo '1970年距今已经有'.time().'秒了!';
?>

date()函数

把时间戳格式化为更易读的日期和时间

用法:date(format,timestamp)

第一个参数:规定时间戳的格式。Y-m-d H:i:s分别代表了‘年月日时分秒’H为24小时制。h为12小时制

第二个参数:规定时间戳。默认是当前时间和日期。

用例:

<?php
	header("Content-Type: text/html;charset=utf-8");
	date_default_timezone_set('PRC');
	$time = time();//当前时间的时间戳
	echo date('Y-m-d H:i:s',$time);//2019-01-30 15:26:08
	echo date('Y-m-d h:i:s',$time);//2019-01-30 03:26:08
?>

microtime()函数

返回的结果是以 "msec sec" 的格式返回一个字符串,其中 sec(时间戳) 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。microtime(true)返回的值是sec+msec的和,保留四位小数。

用法:microtime()

用例:

<?php
	header("Content-Type: text/html;charset=utf-8");
	date_default_timezone_set('PRC');
	echo microtime(true);//1548833794.8092
	echo microtime();//0.06160400 1548833804
?>

相关推荐