search
Homephp教程php手册php 时间日期计算(加减)函数

php 时间日期计算(加减)函数

Jun 13, 2016 am 11:15 AM
mktimephpandfunctionexistusdatetimecalculate

在php中我们要对时间日期加减我们可使用两个函数,mktime与strtotime函数了,下面我来给各位同学介绍它们的使用方法。  

mktime 函数

mktime() 函数返回一个日期的 Unix 时间戳。

参数总是表示 GMT 日期,因此 is_dst 对结果没有影响。

参数可以从右到左依次空着,空着的参数会被设为相应的当前 GMT 值。

参数   描述
hour  可选。规定小时。
minute  可选。规定分钟。
second  可选。规定秒。
month  可选。规定用数字表示的月。
day          可选。规定天。
year  可选。规定年。在某些系统上,合法值介于 1901 - 2038 之间。不过在 PHP 5 中已经不存在这个限制了。
is_dst  可选。如果时间在日光节约时间(DST)期间,则设置为1,否则设置为0,若未知,则设置为-1。

例子

mktime() 函数对于日期运算和验证非常有用。它可以自动校正越界的输入:

 代码如下 复制代码

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)));
?>

输出:

Jan-05-2002
Feb-01-2002
Jan-01-2001
Jan-01-1999


strtotime(time,now)


在一个小项目中要用到环比数据的对比,数据的跨度是一个星期,要做到时间上的定位于是写了两个函数,欢迎拍砖。
计算星期一的日期:

 代码如下 复制代码

function getTheMonday($date) {
 if (date ( 'N', strtotime ( $date ) ) == 1) {
  return date ( 'Y-m-d', strtotime ( 'Monday', strtotime ( $date ) ) );
 } else {
  return date ( 'Y-m-d', strtotime ( 'last Monday', strtotime ( $date ) ) );
 }
}

计算星期天的日期:

 代码如下 复制代码

function getTheSunday($date) { 

return date ( 'Y-m-d', strtotime ( 'Sunday', strtotime ( $date ) ) ); 

 }


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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.