首先,可以通过调用date()函数,将UNIX时间戳格式的数据转换为人类可读的日期格式。
其次,利用strtotime()函数能够将标准的日期字符串反向转换为对应的UNIX时间戳数值。
尽管PHP原生支持日期格式的转换操作,但这种方式可能会消耗PHP解析器的额外处理时间,导致执行速度相对较慢。然而,该方法的显著优点在于其通用性,无论是从数据库查询获取的数据还是其他来源,均能进行转换,且转换范围不受特定格式限制。
具体应用实例
$y=date("Y",time()); //年
$m=date("m",time()); //月
$d=date("d",time()); //日
echo $y."
";
echo $m."
";
echo $d."
";
$eight_clock = mktime(8, 0, 0, $m, $d ,$y); //每天8点
echo date("Y-m-d H:i:s",$eight_clock)."
";
$day_time = mktime(0, 0, 0, $m, 1 ,$y); //每月1号
echo date("Y-m-d H:i:s",$day_time)."
";
相关功能扩展:
// convert a date into a string that tells how long ago
// that date was.... eg: 2 days ago, 3 minutes ago.
function ago($d) {
$c = getdate();
$p = array('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
$display = array('year', 'month', 'day', 'hour', 'minute', 'second');
$factor = array(0, 12, 30, 24, 60, 60);
$d = datetoarr($d);
for ($w = 0; $w < 6; $w++) {
if ($w > 0) {
$c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
$d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
}
if ($c[$p[$w]] - $d[$p[$w]] > 1) {
return ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
}
}
return '';
}
// you can replace this if need be.
// This converts my dates returned from a mysql date string
// into an array object similar to that returned by getdate().
function datetoarr($d) {
preg_match("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2})([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/",$d,$matches);
return array(
'seconds' => $matches[10],
'minutes' => $matches[8],
'hours' => $matches[6],
'mday' => $matches[5],
'mon' => $matches[3],
'year' => $matches[1],
);
}
至此,关于PHP中日期类型转换的实例讲解已介绍完毕。如需了解更多相关内容,建议搜索本站历史文章或继续浏览后续推荐内容,感谢大家的支持!