search
HomeBackend DevelopmentPHP TutorialPHP中UNIX时间戳和日期间的转换与计算实例_PHP

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
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools