search
HomeBackend DevelopmentPHP Tutorial在php和MySql中计算时间差的方法详解_php技巧

在php中计算时间差有时候是件麻烦的事!不过只要你掌握了日期时间函数的用法那这些也就变的简单了。

最近在研究自己爱围脖的时候就要计算到恋爱天数,这需要php根据每天的日期进行计算,下面就来谈谈实现这种日期计算的几种方法:

(1) 如果有数据库就很容易了!若是MSSQL可以使用触发器!用专门计算日期差的函数datediff()便可!若是MYSQL那就用两个日期字段的差值计算的计算结果保存在另一个数值型字段中!用时调用便可!

(2)如果没有数据库,那就得完全用php的时间日期函数!

下面主要说明之:

例:计算1998年5月3日到1999-6-5的天数:

复制代码 代码如下:

$startdate=mktime("0","0","0","5","3","1998"); $enddate=mktime("0","0","0","6","5","1999"); //所得到的值为从1970-1-1到参数时间的总秒数结果是整数.那么下面的代码就好编多了
$days=round(($enddate-$startdate)/3600/24) ;
echo $days;

其中$days为得到的天数;

若mktime()中的参数缺省,那表示使用当前日期,这样便可计算从借书日期至今的天数。

最后说一下SQL的计算方法:

DateDiff 函数

描述:返回两个日期之间的时间间隔。

语法:

DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear>)
interval: 必选。字符串表达式,表示用于计算 date1 和 date2 之间的时间间隔。有关数值,请参阅“设置”部分。

date1, date2: 必选。日期表达式。用于计算的两个日期。

firstdayofweek: 可选。指定星期中第一天的常数。如果没有指定,则默认为星期日。有关数值,请参阅“设置”部分。

firstweekofyear: 可选。指定一年中第一周的常数。如果没有指定,则默认为 1 月 1 日所在的星期。有关数值,请参阅“设置”部分。

interval 参数可以有以下值:

yyyy (年)
q (季度)
m (月)
y (一年的日数)
d (日)
w (一周的日数)
ww (周)
h (小时)
n (分钟)
s (秒)
firstdayofweek 参数可以有以下值:

(以下分别为:常数 值 描述)

vbUseSystem 0 使用区域语言支持 (NLS) API 设置。
vbSunday 1 星期日(默认)
vbMonday 2 星期一
vbTuesday 3 星期二
vbWednesday 4 星期三
vbThursday 5 星期四
vbFriday 6 星期五
vbSaturday 7 星期六
firstweekofyear 参数可以有以下值:

(以下分别为:常数 值 描述)

vbUseSystem 0 使用区域语言支持 (NLS) API 设置。
vbFirstJan1 1 由 1 月 1 日所在的星期开始(默认)。
vbFirstFourDays 2 由在新年中至少有四天的第一周开始。
vbFirstFullWeek 3 由在新的一年中第一个完整的周开始。
说明:DateDiff 函数用于判断在两个日期之间存在的指定时间间隔的数目。

例如可以使用 DateDiff 计算两个日期相差的天数,或者当天到当年最后一天之间的星期数。

要计算 date1 和 date2 相差的天数,可以使用“一年的日数”(“y”)或“日”(“d”)。当 interval 为“一周的日数”(“w”)时,DateDiff 返回两个日期之间的星期数。

如果 date1 是星期一,则 DateDiff 计算到 date2 之前星期一的数目。此结果包含 date2 而不包含 date1。

如果 interval 是“周”(“ww”),则 DateDiff 函数返回日历表中两个日期之间的星期数。函数计算 date1 和 date2 之间星期日的数目。

如果 date2 是星期日,DateDiff 将计算 date2,但即使 date1 是星期日,也不会计算 date1。

如果 date1 晚于 date2,则 DateDiff 函数返回负数。 firstdayofweek 参数会对使用“w”和“ww”间隔符号的计算产生影响。

如果 date1 或 date2 是日期文字,则指定的年度会成为日期的固定部分。但是如果 date1 或 date2 被包括在引号 (“ ”) 中并且省略年份,则在代码中每次计算 date1 或 date2 表达式时,将插入当前年份。这样就可以编写适用于不同年份的程序代码。

在 interval 为“年”(“yyyy”)时,比较 12 月 31 日和来年的 1 月 1 日,虽然实际上只相差一天,DateDiff 返回 1 表示相差一个年份。

DatePart 函数

描述:返回给定日期的指定部分。 语法:

DatePart(interval, date[, firstdayofweek[, firstweekofyear>)
DatePart: 函数的语法有以下参数:
interval: 必选。字符串表达式,表示要返回的时间间隔。有关数值,请参阅“设置”部分。
date: 必选。要计算的日期表达式。
firstdayofweek: 可选。指定星期中的第一天的常数。如果没有指定,则默认为星期日。有关数值,请参阅“设置”部分。
firstweekofyear: 可选。指定一年中第一周的常数。如果没有指定,则默认为 1 月 1 日所在的星期。有关数值,请参阅“设置”部分。
其中interval 参数可以有以下值: yyyy (年) 、q (季度) 、m (月) 、y (一年的日数) 、d (日) 、w (一周的日数) 、ww (周) 、h (小时) 、n (分钟) 、s (秒)

其中firstdayofweek 参数可以有以下值:

(以下分别为:常数 值 描述)

vbUseSystem 0 使用区域语言支持 (NLS) API 设置。
vbSunday 1 星期日(默认)
vbMonday 2 星期一
vbTuesday 3 星期二
vbWednesday 4 星期三
vbThursday 5 星期四
vbFriday 6 星期五
vbSaturday 7 星期六
firstweekofyear 参数可以有以下值:

(以下分别为:常数 值 描述)

vbUseSystem 0 使用区域语言支持 (NLS) API 设置。
vbFirstJan1 1 由 1 月 1 日所在的星期开始(默认)。
vbFirstFourDays 2 由在新年中至少有四天的第一周开始。
vbFirstFullWeek 3 由在新的一年中第一个完整的周(不跨年度)开始。
说明:DatePart 函数用于计算日期并返回指定的时间间隔。例如使用 DatePart 计算某一天是星期几或当前的时间。

其中firstdayofweek 参数会影响使用“w”和“ww”间隔符号的计算。

如果 date 是日期文字,则指定的年度会成为日期的固定部分。但是如果 date 被包含在引号 (“ ”) 中,并且省略年份,则在代码中每次计算 date 表达式时,将插入当前年份。这样就可以编写适用于不同年份的程序代码!

以上所述就是本文的全部内容了,希望能够对大家熟练掌握php有所帮助。

请您花一点时间将文章分享给您的朋友或者留下评论。我们将会由衷感谢您的支持!

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 Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

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