Home Backend Development PHP Tutorial PHP中UNIX时间戳和日期间的转换与计算实例_PHP

PHP中UNIX时间戳和日期间的转换与计算实例_PHP

May 31, 2016 pm 07:27 PM
php unix timestamp date calculate Convert

UNIX时间戳是保存日期和时间的一种紧凑简洁的方法,是大多数UNIX系统中保存当前日期和时间的一种方法,也是在大多数计算机语言中表示日期和时间的一种标准格式。以32位整数表示格林威治标准时间,例如,使用证书11230499325表示当前时间的时间戳。UNIX时间戳是从1970年1月1日零点(UTC/GMT的午夜)开始起到当前时间所经过的秒数。1970年1月1日零点作为所有日期计算的基础,这个日期通常成为UNIX纪元。

因为UNIX时间戳是一个32位的数字格式,所以特别适用于计算机处理,例如计算两个时间点之间相差的天数。另外,由于文化和地区的差异,存在不同的时间格式,以及时区的问题。所以UNIX时间戳也是根据一个时区进行标准化而设计的一种通用格式,并且这种格式可以很容易地转换为任何格式。也因为UNIX时间戳是一个32位的证书表示的,所以在处理1902年以前或2038年以后的事件将会遇到一些问题。另外,在Windows下,由于时间戳不能为负数,所以使用PHP中提供的时间戳函数处理1970年之前的日期,就会发生错误。要使PHP代码具有可移植性,必须记住这一点。

将日期和时间转变成UNIX时间戳

在PHP中,如果需要将日期和时间转变成UNIX时间戳,可以调用mktime()函数。该函数的原型如下所示:

代码如下:


int mktime([int hour [,int minute[,int second[,int month[,int day[int year]]]]]])


该函数中所有参数都是可选的,如果参数为空,默认将当前时间转变成UNIX时间戳。这样,和直接调用time()函数获取当前的UNIX时间戳功能相同。参数也可以从右向左省略,任何省略的参数会被设置成本地日期和时间的当前值。如果只想转变日期,对具体的时间不在乎,可以将前三个转变时间的参数都设置为0.mktime()函数对于日期运算和验证非常有用,它可以自动校政越界的输入。如下所示:

代码如下:


echo date("Y-m-d",mktime(0,0,0,12,36,2008))."\n";    //日期超过31天,计算后输出 2009-01-05
echo date("Y-m-d",mktime(0,0,0,14,1,2010))."\n";     //月份超过12月,计算后输出2011-02-01
echo date("Y-m-d",mktime(0,0,0,1,1,2012))."\n";      //没有问题的转变,输出结果2012-01-01
echo date("Y-m-d",mktime(0,0,0,1,1,99))."\n";        //会将99年转变为1999年, 1990-01-01
?>

如果有需要将任何英文文本的日期时间描述直接解析为UNIX时间戳,可以使用strtotime()函数,该函数的圆形如下所示:

代码如下:


int strtotime(string time[,int now])

函数strtotime()可以用英语的自然语言创建讴歌时刻的时间戳,接受一个包含美国英语日期格式的字符串并尝试将其解析为UNIX时间戳(自January 1 1970 00:00:00 GMT起的描述),其值相对于now参数给出的时间,如果没有提供次参数则用系统当前时间。该函数执行成功则返回时间戳,否则返回FALSE。和mktime()的对比如下所示:

代码如下:


echo date("Y-m-d", strtotime("now"));                  //输出现在的时间戳
echo date("Y-m-d", strtotime("8 may 2012"));           //输出2012-05-08
echo date("Y-m-d", strtotime("+1 day"));               //输出现在的日期加1天
echo date("Y-m-d", strtotime("last monday"));          //输出2012-04-02
?>

下例通过使用strtotime()函数编写一个纪念日的倒计时程序,来介绍一下该函数在项目开发中的实际应用,示例代码如下所示:

代码如下:


$now =strtotime("now"); //当前时间
$endtime= strtotime("2014-08-18 08:08:08"); //设定毕业时间,转成时间戳
 
$second = $endtime-$now; //获取毕业时间到现在时间的时间戳(秒数)
$year = floor($second/3600/24/365); //从这个时间戳中换算出年头数
 
$temp =$second-$year*365*24*3600; //从这个时间戳中去掉整年的秒数,就剩下月份的秒数
$month=floor($temp/3600/24/30); //从这个时间戳中共换算出月数
 
$temp=$temp-$month*30*3600*24; //从时间戳中去掉整月的秒数,就剩下天的描述
$day = floor($temp/24/3600); //从这个时间戳中换算出剩余的天数
 
$temp=$temp-$day*3600*24; //从这个时间戳中去掉整天的秒数,就剩下小时的秒数
$hour = floor($temp/3600); //从这个时间戳中换算出剩余的小时数
 
$temp=$temp- $hour*3600; //从时间戳中去掉小时的秒数,就剩下分的秒数
$minute=floor($temp/60); //从这个时间戳中换算出剩余的分数
 
$second1=$temp-$minute*60; //最后只有剩余的秒数了
 
echo "距离培训毕业还有($year)年($month)月($day)天($hour)小时($minute)分($second1)秒。";
?>

注意:如果给定的年份是两位数字的格式,则其值0-69表示2000-2069,70-100表示1970-2000。

日期的计算

在PHP中,计算两个日期之间相隔的长度,最简单的方法就是通过计算两个UNIX时间戳之差来获得。例如,在PHP脚本中接收来自HTML表单用户提交的出生日期,计算这个用户的年龄。如下所示:

代码如下:


//从表单中接收用户提交的出生日期中的年份、月份、天
$year = 1981;
$month = 11;
$day = 05;
$birthday = mktime(0,0,0,$month,$day,$year); //将出生日期转变为UNIX时间戳
$nowdate = time(); //调用time()函数获取当前时间的UNIX时间戳
$ageunix = $nowdate -$birthday; //两个时间戳相减获取用户年龄的UNIX时间戳
$age = floor($ageunix/3600/24/365); //将UNIX时间戳除以一年的秒数获取用户的年龄
echo "年龄:$age";
 
?>

在以上的脚本中,调用mktime()函数将从用户出生日期转变为UNIX时间戳,再调用time()函数获取当前时间的UNIX时间戳。因为这个日期的格式都是使用整数表示的,所以可以将他们相减。又将计算后获取的UNIX时间戳除以一年的秒数,将UNIX时间戳转变为以年度量的单位。

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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

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

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

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