广告
返回顶部
首页 > 资讯 > 后端开发 > PHP编程 >php中日期类型转换实例讲解
  • 921
分享到

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

2024-04-02 19:04:59 921人浏览 安东尼
摘要

1、使用date()函数将UNIX时间戳转换为日期。 2、使用strtotime()函数将日期转换为UNIX时间戳。 在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]]).' '.$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中日期类型转换实例讲解的文章就介绍到这了,更多相关php中日期类型的转换内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: php中日期类型转换实例讲解

本文链接: https://www.lsjlt.com/news/134326.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作