search
HomeBackend DevelopmentPHP TutorialPHP date and time operations

PHP date and time operations

Oct 14, 2019 pm 04:52 PM
dateTimestamp

Date and time are usually used for display and conditional restrictions in programming languages. More specifically, you may want to display the time in a certain format, display the time in a certain time zone, get the time after one week, get the timestamp of the beginning of this week, convert the time in a certain format into another, etc. wait.

1. Display the current time

Use the date function, the format is date(format[, timestamp]), which accepts two parameters, The first parameter is a time format string, and the second parameter is a timestamp. The timestamp is optional. If not filled in, it will be the timestamp of the current time.

echo date('Y-m-d H:i:s');  // 2018-12-25 09:31:22

Like this, you can print out the current year, month, day, hour, minute and second. Of course, you can also print out the time in other formats depending on the format string:

echo date('l dS \of F Y h:i:s A');  // Tuesday 25th of December2018 09:34:54 AM

Explain what is used above Format characters:

Y Complete year, 4 digits

m Month with leading 0

d The day of the month, with a leading 0

H Hour in the 24-hour format, with a leading 0

i Minutes, with a leading 0

s Seconds, with leading 0

l The complete English version of the day of the week (note the lowercase L, not the uppercase i)

S ​​The suffix of the number of days in the month (may be st, nd, rd, th)

F The complete English of the month

h 12-hour hour, with leading 0

A Morning or afternoon (AM or PM)

This is just a list For some of them, you can check the official manual for more complete format characters.

2. Display the world in a certain time zone

For example, by setting the time zone, we can get the time in the United States:

date_default_timezone_set("America/New_York");
echo date('Y-m-d H:i:s');  // 2018-12-24 20:54:36

The above is the world of New York, USA. You can check the PHP documentation for the string required by the time zone. If it is illegal, a warning will be generated. At the same time, the time zone will not be set successfully, but the default time zone will be used.

3. Calculated time

For example, the time at the beginning of this week, the beginning of this month, the time after one week, etc., you can Use the strtotime function to do this for us.

strtotime(time[, now = time()]) can convert any string describing time and date into a unix timestamp. The first parameter is the description string, and the second parameter is used to calculate timestamp (defaults to the current timestamp). You can tell from the description that it is a very flexible function, but be aware that it is a function after all. It is not so smart that it can understand "any" string describing time. It still needs a specific format - especially in China. , don’t expect it to understand what “December 25, 2018” means. But it is still very powerful and can do all the functions described previously.

echo '下个星期的时间:' . date('Y-m-d H:i:s', strtotime('+1 week'));  // 下个星期的时间:2019-01-01 10:12:16
echo '本周开始时间:' . date('Y-m-d H:i:s', strtotime('this week Monday'));  // 本周开始时间:2018-12-24 00:00:00
echo '明天开始时间:' . date('Y-m-d 00:00:00', strtotime('+1 day'));  // 明天开始时间:2018-12-26 00:00:00
echo '1天2小时3分5秒之后的时间:' . date('Y-m-d H:i:s', strtotime('+1 day 2 hours 3 minutes 5 seconds'));  // 1天2小时3分5秒之后的时间:2018-12-26 12:24:15

4. Create a time based on specific values

If you know the year, month, day, hour, minute, and second of a certain time , if you want to use them to create a time, you can choose to splice them into a time string and then use strtotime to parse it, or in this case you can also use a more reliable method: mktime.

mktime(hour, minute, second, month, day, year) It should be noted that the order of parameters is not the same as our habits, which is: hour, minute, second, month, day, year

$time = mktime(3, 10, 15, 2, 15, 2014);
echo date('Y-m-d H:i:s', $time);  // 2014-02-15 03:10:15

5. Time operations of object types

php also supports time operations of object types

$date_obj = date_create();  // 创建一个DateTime对象
echo $date_obj->format('Y-m-d H:i:s');  // 2018-12-25 10:45:08
 
date_add($date_obj, date_interval_create_from_date_string("3 days"));  // 给对象增加3天
echo $date_obj->format('Y-m-d H:i:s');  // 2018-12-28 10:45:08
 
date_sub($date_obj, date_interval_create_from_date_string("2 days"));  // 给对象减少2天
echo $date_obj->format('Y-m-d H:i:s');  // 2018-12-26 10:45:08
 
echo '时区为:' . timezone_name_get(date_timezone_get($date_obj));  // 时区为:PRC (中国时区,获取时区并打印)

It is different from the procedural style, but it can be implemented The functions are actually quite similar.

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of PHP date and time operations. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:www.kanoseo.cn. If there is any infringement, please contact admin@php.cn delete
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

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor