search
HomeBackend DevelopmentPHP TutorialSummary of date and time operations in PHP_PHP tutorial

//Encode of GB2312
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);

/*Focus on understanding the strtotime() function
1. strftime is easier to use than time(). It can directly convert the commonly used '2010-02-03' into a timestamp.
2. date() can display the time before 1970. Instead of using negative numbers as parameter 2
3. Date calculation can be transferred using timestamp. To calculate the number of days difference between two dates, you can get the difference timestamp and divide it by "24 hours * 60 minutes * 60" seconds, but it is more concise to use strtotime()
4. Learn how to create a calendar using PEAR. Omit it here.
Knowledge point: There is date(Y-m-d,-800) on the Internet to calculate the time before 1970, but the WINDOW system does not support negative values, so it will always return 1970-1-1 midnight.
*/

#PHP5 must set the default zone first.
date_default_timezone_set(ETC/GMT-8);
$nowdate=2010-02-23;
$lassdate = 2010-02-22;

The echo strftime() function outputs .strftime(%Y-%m-%d %H:%M:%S,time()).
;
The echo date() function outputs .date(Y-m-d H:i:s,time()).
;
//Check date: boolean checkdate(int month,int day,int year)
$d=2010-2-31;
echo $d.Yes.(checkdate(2,31,2010)? Valid date!: Invalid date!).
;


//Determine the number of days in the month
echo There are .date(t,time()).days this month
; //28 days
//Determine the number of days in any given month
$d=2008-02-01; //Leap year, or $d=2008-02; You don’t need to enter the day
$d=strtotime($d);
echo There are .date(t,$d).days in February 2008
; //29 days

$d=getdate();
echo

;<br>
print_r($d);<br>
echo 
;
/*Array(
[seconds] => 42
[minutes] => 16
[hours] => 13
[mday] => 23
[wday] => 2
[mon] => 2
[year] => 2010
[yday] => 53
[weekday] => Tuesday
[month] => February
[0] => 1266902202
)
*/

//echo date("Y-m-d H:i:s",-8000);
//setlocale(LC_ALL,zh_CN.gb2312); //The setlocale function has no effect on the following.
#Test strftime, mktime functions.
echo strftime(Today is: %Y-%m-%d %H:%M:%S).
;
echo strtotime(now).
; // Equivalent to time(), but the usage range of strtotime is more flexible, see below.
echo test to restore yesterday's time:.date(Y-m-d,strtotime($lassdate)).
; //You can convert the string date into a timestamp and then use date to convert it back to the original format.
$x=strtotime($lassdate);
$y=mktime(0,0,0,2,22,2010);
Yesterday's timestamp obtained by echo strtotime() is: .$x., yesterday's timestamp obtained by mktime() is: .$y.(($x==$y)?, the two are equal:, the two are not Same).
; //Equal.

#Show dates before 1970
$time_int=strtotime(1929-2-10);
echo date("Y-m-d ",$time_int).
; //The same function as the date() function in MYSQL is date_format(1996-02-05 11:07:45,%Y-%m -%d) or for_format()

/*Time operation:
*Please use method three. Other methods are for reference only. *
*/
#1. Today is the 23rd. Get the time of the day before yesterday, that is, minus two days.
$predate=2;
$pretime=$predate*24*60*60; //2-day timestamp.
echo date(The day before yesterday was: Y-m-d, time()-$pretime).
; //The day before yesterday was: 2010-02-21

#2, The number of days difference between two dates.
$olddate = 2010-02-11; //If you want to use the mktime function, you need to use explode to disassemble the date.
$oldtime = strtotime($olddate);
$passtime = time()-$oldtime; //Elapsed timestamp.
echo You've been online.floor($passtime/(24*60*60)) for days.
; //12 days.

#3. This time last year. Leap years should be taken into account when using: 365 days in an ordinary year and 366 days in a leap year.
#Method 1: Get the timestamp minus the number of days in the year.
$yDate=1;
$yDate_Y=date(Y,time())-1; //Year-1, that is, last year
$yDateYMD="$yDate_Y-01-01";
$yYMD=strtotime($yDateYMD); //The timestamp of January 1 last year.
$d=date(L,$yYMD)?366:365; //Is it a leap year
$yYearTime=$d*24*60*60;

$yYear=date(Y-m-d,time()-$yYearTime);
echo "Today last year: $yYear
"; //2009-02-23
#Method 2: Use the year that directly intercepts the current date and subtract one, but it is not rigorous and does not take leap years into account.
#Calculate 60 years ago today. Ignore any leap years that pass.
$yDate_Y=$yDate_Y-59;
$md=explode(-,date(Y-m-d));
$yYMD="$yDate_Y-{$md[1]}-{$md[2]}";
echo "60 years ago today: $yYMD
"; //1950-02-23

#Method 3: Use strtotime() and GNU date syntax---------Recommended!
//3 days later; //The current time is 2010-02-23
$d=strtotime(3 days);
echo 3 days later.date(Y-m-d,$d)."
";
//3 days ago:
$d=strtotime(-3 days);
echo 3 days ago.date(Y-m-d,$d)."
"; //2010-02-20
//One month ago:
$d=strtotime(-1 months);
echo one month ago.date(Y-m-d,$d)."
"; //2010-01-23

//2 months later:
$d=strtotime(2 months);
echo two months later.date(Y-m-d,$d)."
"; //2010-04-23

//1 year ago:
$d=strtotime(-1 years);
echo 1 year ago.date(Y-m-d,$d)."
"; //2009-02-23

//2 hours ago:
$d=strtotime(-2 hours);
echo Current: .date(Y-m-d H:i:s,time())., 2 hours ago.date(Y-m-d H:i:s,$d)."
"; //Currently: 2010 -02-23 13:38:49, 2 hours ago 2010-02-23 11:38:49

#DateTime constructor: object DateTime([string $time [,dateTimeZone $timezone])
$date = new DateTime(2010-02-23 12:26:36);
echo $date->format(Y-m-d H:i:s)."
"; //Same as date() function. 2010-02-23 12:26:36
//Reset time:
//1. Reset date: boolean setDate(int year,int month,int day)
//2. Reset time: boolean setDate(int hour,int minute[,int second])
$date->setDate(2010,2,28);
echo $date->format(Y-m-d H:i:s)."
"; //2010-02-28 12:26:36
//Date calculation, equivalent to strtotime()
above $date->modify("+7 hours");
echo $date->format(Y-m-d H:i:s)."
"; //2010-02-28 19:26:36
$date->modify("3 days");
echo $date->format(Y-m-d H:i:s)."
"; //2010-03-03 19:26:36 //Start from the 28th that was changed above

/*PHP5 does not support the money_format function in WIN?
setlocale(LC_MONETARY,zh_CN);
echo money_format("%i",786.56);//?Fatal error: Call to undefined function money_format()
*/
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508431.htmlTechArticle?php //Encode header of GB2312 (Cache-Control: no-store, no-cache, must-revalidate ); header(Cache-Control: post-check=0, pre-check=0, false); /*Focus on understanding strtotime() function 1, strf...
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 Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

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 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.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools