Home  >  Article  >  Backend Development  >  How to convert to date in php

How to convert to date in php

藏色散人
藏色散人Original
2023-01-20 09:28:183618browse

php实现转换为日期的方法:1、使用“strtotime()”函数将日期转换为UNIX时间戳;2、使用“date()”函数将UNIX时间戳转换为日期;3、通过“echo date("Y-m-d H:i:s",$day_time)”输出转换日期即可。

How to convert to date in php

本教程操作环境:Windows10系统、PHP8.1版、DELL G3电脑

php怎么实现转换为日期?

php中日期类型转换实例讲解

1、使用date()函数将UNIX时间戳转换为日期。

2、使用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]]).&#39; &#39;.$display[$w].&#39;s ago&#39;;
 }
 }
 return &#39;&#39;;
}
// 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( 
 &#39;seconds&#39; => $matches[10], 
 &#39;minutes&#39; => $matches[8], 
 &#39;hours&#39; => $matches[6], 
 &#39;mday&#39; => $matches[5], 
 &#39;mon&#39; => $matches[3], 
 &#39;year&#39; => $matches[1], 
 );
}

推荐学习:《PHP视频教程

The above is the detailed content of How to convert to date in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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