Home Backend Development PHP Tutorial 非常全面的php日期时间运算汇总

非常全面的php日期时间运算汇总

Jun 13, 2016 am 10:31 AM

这篇文章主要整理了关于php日期时间运算相关内容,涉及知识点较为全面,感兴趣的小伙伴们可以参考一下

实例讲解之前,先来介绍几个核心函数: 

mktime 函数

mktime() 函数返回一个日期的 Unix 时间戳。
参数总是表示 GMT 日期,因此 is_dst 对结果没有影响。
参数可以从右到左依次空着,空着的参数会被设为相应的当前 GMT 值。
语法:mktime(hour,minute,second,month,day,year,is_dst)

参数               描述 
hour       可选。规定小时。 
minute   可选。规定分钟。 
second   可选。规定秒。 
month    可选。规定用数字表示的月。 
day         可选。规定天。 
year        可选。规定年。在某些系统上,合法值介于 1901 - 2038 之间。不过在 PHP 5 中已经不存在这个限制了。 
is_dst  可选。如果时间在日光节约时间(DST)期间,则设置为1,否则设置为0,若未知,则设置为-1。  
自 5.1.0 起,is_dst 参数被废弃。因此应该使用新的时区处理特性。  
例子:mktime() 函数对于日期运算和验证非常有用。它可以自动校正越界的输入:  

<?php 
echo(date("M-d-Y",mktime(0,0,0,12,36,2001))); 
echo(date("M-d-Y",mktime(0,0,0,14,1,2001))); 
echo(date("M-d-Y",mktime(0,0,0,1,1,2001))); 
echo(date("M-d-Y",mktime(0,0,0,1,1,99))); 
?>
Copy after login

输出:

Jan-05-2002 
Feb-01-2002 
Jan-01-2001 
Jan-01-1999
Copy after login

strtotime 函数

strtotime() 函数将任何英文文本的日期时间描述解析为 Unix 时间戳。
语法:strtotime(time,now)

参数 描述
time 规定要解析的时间字符串。
now 用来计算返回值的时间戳。如果省略该参数,则使用当前时间。
一周之后: strtotime("+1 week") ;
一周之前: strtotime("-1 week") ;
一月之后: strtotime("+1 months") ;
一天之后: strtotime("+1 days") ;
30秒之后 strtotime( " +30 seconds " );
20分钟之后 strtotime( " +20 minutes " );
12个小时之后 strtotime( " +12 hours " );

date 函数
date() 函数格式化一个本地时间/日期。
语法
date(format,timestamp)
date_default_timezone_set 函数
date_default_timezone_set() 函数设置用在脚本中所有日期/时间函数的默认时区。
date_default_timezone_set(timezone)

实例

第一种情况是没有数据库,只是得到的日期值进行比较的话,那就得完全用php的时间日期函数计算了,如下:

比如要计算2015-9-5到2015-9-18还有多少天:

<?php 
$startdate=strtotime("2015-9-5"); 
$enddate=strtotime("2015-9-18"); //上面的php时间日期函数已经把日期变成了时间戳,就是变成了秒。这样只要让两数值相减,然后把秒变成天就可以了,比较的简单,如下: 
$days=round(($enddate-$startdate)/3600/24) ; 
echo $days; //days为得到的天数; 
?>
Copy after login

第二种 孩子的成长

 <? 
date_default_timezone_set(&#39;Asia/Shanghai&#39;); 
//以上一句为设置时区,其实不设也行,但是zde debug的时候会有提示,说什么不安全的函数…添上吧。 
 
echo date(&#39;Y-m-d H:i:s&#39;).&#39; 今天是&#39;.date(&#39;Y&#39;).&#39;年的第&#39;.date(&#39;W&#39;).&#39;周&#39;; 
 
$stime=&#39;2005-11-03 10:08&#39;; 
echo "<br/><br/>***自出生(<font color=blue>$stime</font>)以来…:<br/><br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(daysofnow($stime),3)."</b></font>天<br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(weeksofnow($stime),3)."</b></font>周<br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(monthsofnow($stime),3)."</b></font>个月<br/>"; 
echo "今天是第<font color=red><b>".Lnbsp(yearsofnow($stime),3)."</b></font>年<br/>"; 
/* 
$output=sprintf(" 今天是第<font color=red><b>%03d</b></font>天<br/>今天是第< font color=red><b>%03d</b></font>周<br/>今天是第< font color=red><b>%03d</b></font>个月<br/>今天是第< font color=red><b>%03d</b></font>年<br/& gt;",daysofnow($stime),weeksofnow($stime),monthsofnow($stime),yearsofnow($stime)); 
echo $output; 
*/ 
 
function weeksofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 $fweeks=date(&#39;w&#39;,$ftime); 
 if ($fweeks==0) $fweeks=7; 
 $nweeks=date(&#39;w&#39;); 
 if ($nweeks==0) $nweeks=7; 
 $ftemp=strtotime(date(&#39;Y-m-d 00:00:00&#39;,$ftime))-$fweeks*60*60*24; 
 $ntemp=strtotime(date(&#39;Y-m-d 00:00:00&#39;,time()))+(7-$nweeks)*60*60*24; 
 //echo date(&#39;w&#39;,$ftemp)."<br/>....<br/>".date(&#39;w&#39;,$ntemp)."<br/>"; 
 return ($ntemp-$ftemp)/60/60/24/7; 
} 
 
function daysofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 return ceil(abs((time()-$ftime)/(60*60*24))); 
} 
 
function monthsofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 $fmonth=date(&#39;m&#39;,$ftime); 
 $fyear=date(&#39;Y&#39;,$ftime); 
 $nmonth=date(&#39;m&#39;); 
 $nyear=date(&#39;Y&#39;); 
 $result=($nyear-$fyear)*12+$nmonth-$fmonth+1; 
 return $result; 
} 
 
function yearsofnow($stime) 
{ 
 $ftime=strtotime($stime); 
 $fyear=date(&#39;Y&#39;,$ftime); 
 $nyear=date(&#39;Y&#39;); 
 return $nyear-$fyear+1; 
} 
 
// 下面的函数只是加空格用的,不是核心内容,只为美观 
function Lnbsp($data,$num) 
{ 
 $result=trim($data); 
 for($i=$num;$i>=strlen($data);$i--) { 
 $result=&#39; &#39;.$result; 
 } 
 return $result; 
} 
?>
Copy after login

第三种 情况:明天,下个月和明年的日期,就可以用以下的代码:

$tomorrow = date(&#39;Y-m-d&#39;,mktime (0,0,0,date("m"),date("d")+1,date("Y"))); 
$nextmonth = date(&#39;Y-m&#39;,mktime (0,0,0,date("m")+1,date("d")+1,date("Y"))); 
$nextyear = date(&#39;Y&#39;,mktime (0,0,0,date("m"),date("d"),date("Y")+1)); 
 
echo $tomorrow.&#39;<br/>&#39;; 
echo $nextmonth.&#39;<br/>&#39;; 
echo $nextyear.&#39;<br/>&#39;;
Copy after login

第四种情况:工作时间(刨除假日)

<? 
$startDate="2001-12-12"; 
$endDate="2002-11-1"; 
 
$holidayArr=array("05-01","05-02","10-01","10-01","10-02","10-03","10-04","10-05","01-26","01-27","01-28","01-29"); 
 //假期日期数组,比方国庆,五一,春节等 
$endWeek=2; 
 //周末是否双休.双休为2,仅仅星期天休息为1,没有休息为0 
 
$beginUX=strtotime($startDate); 
$endUX=strtotime($endDate); 
 
for($n=$beginUX;$n<=$endUX;$n=$n+86400){ 
 $week=date("w",$n); 
 $MonDay=date("m-d",$n); 
 if($endWeek){//去处周末休息 
 if($endWeek==2){ 
 if($week==0||$week==6) continue; 
 } 
 if($endWeek==1){ 
 if($week==0) continue; 
 } 
 } 
 if(in_array($MonDay,$holidayArr)) continue; 
 $totalHour+=10;//每天工作10小时 
} 
echo "开始日期:$startDate<BR>"; 
echo "结束日期:$endDate<BR>"; 
echo "共花了".$totalHour."小时"; 
?>
Copy after login

第五种情况:给出秒算小时

<?php 
function transform($sec){ 
 $output = &#39;&#39;; 
 $hours = floor($sec / 3600); 
 $remainSeconds = $sec % 3600; 
 $minutes = floor($remainSeconds / 60); 
 $seconds = $sec - $hours * 3600 - $minutes * 60; 
 if($sec >= 3600){ 
 $output .= $hours.&#39; h / &#39;; 
 $output .= $minutes.&#39; m / &#39;; 
 } 
 if($sec >= 60 && $sec < 3600){ 
 $output .= $minutes.&#39; m / &#39;; 
 }
 return $output .= $seconds.&#39; s &#39;; 
} 
echo transform(3231803); 
?>
Copy after login

以上就是为大家提供的php日期时间运算全部实例,希望对大家的学习有所帮助。

更多相关教程请访问 php编程从入门到精通全套视频教程

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles