search
HomeBackend DevelopmentPHP TutorialTips for using date and time functions in PHP_PHP Tutorial

Tips for using date and time functions in PHP_PHP Tutorial

Jul 21, 2016 pm 03:51 PM
datephpandcodeusefunctioncopyYearSkilldatetimeof

PHP’s date and time function date()

1, year-month-day

Copy code The code is as follows:

echo date('Y-m-j');
2007-02-6

echo date('y-n-j');
07 -2-6

Uppercase Y represents the four-digit year, while lowercase y represents the two-digit year;
Lowercase m represents the number of the month (with leading), while lowercase n represents Month number without leading.
Copy code The code is as follows:

echo date('Y-M-j');
2007-Feb-6

echo date('Y-m-d');
2007-02-06

Capital M represents the 3 abbreviation characters of the month, while lowercase m represents the month Numbers (with leading 0);
There is no uppercase J, only lowercase j represents the date of the month, without leading o; if the month needs to be preceded, use lowercase d.
Copy code The code is as follows:

echo date('Y-M-j');
2007-Feb-6

echo date('Y-F-jS');
2007-February-6th

Capital M represents the 3 abbreviation characters of the month, while capital F represents the English of the month Write in full. (No lowercase f)
Capital S represents the suffix of the date, such as "st", "nd", "rd" and "th", depending on the date number.

Summary:
can use uppercase Y and lowercase y to represent the year;
can use uppercase F, uppercase M, lowercase m and lowercase n to represent the month (two ways to represent characters and numbers respectively) );
can use lowercase d and lowercase j to represent the day, and uppercase S represents the suffix of the date.


2, hour:minute:second

By default, the time displayed by PHP interpretation is "Greenwich Mean Time", which is 8 hours different from our local time.
Copy code The code is as follows:

echo date('g:i:s a');
5: 56:57 am

echo date('h:i:s A');
05:56:57 AM

lowercase g indicates 12-hour format, without leading 0, while a lowercase h indicates a 12-hour clock with leading 0s.
When using the 12-hour clock, you need to indicate morning and afternoon. Lowercase a represents lowercase "am" and "pm", and uppercase A represents uppercase "AM" and "PM".
Copy code The code is as follows:

echo date('G:i:s');
14:02 :26

Capital G represents the hour in 24-hour format, but without leading; use capital H to represent the hour in 24-hour format with leading

Summary:
The letter g represents the hour without a leading, and the letter h represents the hour with a leading;
Lowercase g and h represent the 12-hour format, and capital G and H represent the 24-hour format.

3, leap year, week, day
Copy code The code is as follows:

echo date('L ');
Whether this year is a leap year: 0

echo date('l');
Today is: Tuesday

echo date('D');
Today Yes: Tue

Capital L indicates whether this year is a leap year, Boolean value, returns 1 if true, otherwise 0;
Lowercase l indicates the full English version of the day of the week (Tuesday);
Use a capital D to represent the 3-character abbreviation of the day of the week (Tue).
Copy code The code is as follows:

echo date('w');
Today's week: 2

echo date('W');

This week is the 06th week of the year

lowercase w represents the day of the week, and the number form represents
uppercase W Represents the number of weeks in the year
Copy code The code is as follows:

echo date('t');
This month is 28 days

echo date('z');

Today is the 36th day of this year

Lowercase t indicates the number of days in the current month
Lowercase z indicates the day of the year today

4, others

echo date('T');
UTC
Capital T represents the server's time locale

echo date('I');
0
Capital I represents Determine whether the current daylight saving time is, return 1 if true, otherwise 0

echo date('U');
1170769424
uppercase U represents the total number of days from January 1, 1970 to the present The number of seconds is the UNIX timestamp of the Unix time epoch.

echo date('c');
2007-02-06T14:24:43+00:00
Lowercase c represents the ISO8601 date, the date format is YYYY-MM-DD, using letters T to separate the date and time, the time format is HH:MM:SS, and the time zone is represented by the offset from Greenwich Mean Time (GMT).

echo date('r');
Tue, 06 Feb 2007 14:25:52 +0000
Lowercase r represents the RFC822 date.

The small date() function shows the power and charm of PHP. Let’s compare it to ASP, haha.

PHP date time function date time: How to display the current system time and synchronize the clock

Tell you a simple method:
The result is: 2009-10-06 16:21:38
time() function: displays the current time of the system.
date() function: Format the server's time.

Syntax: string date(string format, int [timestamp]);
Function type: Time and date
Return value: String

The parameters are as follows:
a - "am" or "pm"
A - "AM" or "PM"
d - day, two digits, if there are less than two digits, add zero in front; for example: "01" to "31" "
D - day of the week, three English letters; such as: "Fri"
F - month, full English name; such as: "January"
h - hour in 12-hour format; such as: "01 " to "12"
H - hours in 24-hour format; such as: "00" to "23"
g - hours in 12-hour format, no zeros are added for less than two digits; such as: "1" to 12 "
G - hour in 24-hour format, no zeros are added for less than two digits; such as: "0" to "23"
i - minutes; such as: "00" to "59"
j - number Day, two digits, if there are less than two digits, do not add zeros; For example: "1" to "31"
l - Day of the week, full English name; For example: "Friday"
m - Month, two digits , if there are less than two digits, add zeros in front; for example: "01" to "12"
n - month, two digits, if there are less than two digits, do not add zeros; for example: "1" to "12"
M - month, three English letters; such as: "Jan"
s - seconds; such as: "00" to "59"
S - add an English ordinal at the end of the word, two English letters; such as: "th", "nd"
t - the number of days in the specified month; such as: "28" to "31"
U - the total number of seconds
w - the numeric day of the week, such as: "0" (Sunday) to "6" (Saturday)
Y - year, four digits; such as: "1999"
y - year, two digits; such as: "99"
z - year The number of days; such as: "0" to "365"
If the displayed time is inconsistent with the system, you need to change the PHP.ini configuration file
The system default is UTC time
You can open php.inc.
Set date.timezone = PRC

Advanced application skills of PHP date and time functions

The PHP date and time function is introduced in date() Simple usage, this class will introduce more functions to enrich our application

checkdate($month,$date,$year)

If the applied value constitutes a valid date, then the function returns true. For example, for the error date February 31, 2005, this function returns false.

This function can be used to check and validate a date before it is used in calculations or saved in the database.
Copy code The code is as follows:

// returns false
echo checkdate(2 ,30,2005) ? "valid" : "invalid";
// returns true
echo checkdate(4,6,2010) ? "valid" : "invalid";
?>

getdate($ts)

Without arguments, this function returns the current date and time in a combined array. Each element in the array represents a specific component of the date/time value. An optional time stamp argument can be submitted to the function to obtain a date/time value corresponding to the time stamp.

Apply this function to obtain a series of discrete, easily separable date/time values.

Copy code The code is as follows:

// get date as associative array
$arr = getdate();
echo "Date is " . $arr['mday'] . " " . $arr['weekday'] . " " . $arr['year'];
echo "Time is " . $arr['hours'] . ":" . $arr['minutes'];
?>

mktime($hour, $minute, $second, $month, $day, $year)

This function has the opposite effect of getdate(): it consists of a A series of date and time values ​​generates a UNIX time stamp (the number of seconds elapsed since January 1, 1970 GMT). When no arguments are used, it generates a UNIX time stamp of the current time.

Use this function to obtain the UNIX time label of the immediate time. Such timestamps are commonly used in many databases and programming languages.

Copy code The code is as follows:

// returns timestamp for 13:15 :23 7-Jun-2006
echo mktime(13,15,23,6,7,2006);
?>

date($format, $ ts)

This function formats a UNIX time stamp into a human-readable date string. It is the most powerful function in the PHP date/time API and can be used to convert integer time labels into the required string format in a series of correction values.

Apply this function when formatting time or date for display.

Copy code The code is as follows:

// format current date
// returns "13-Sep-2005 01:16 PM"
echo date("d-M-Y h:i A", mktime());
?>

strtotime($str)

This function converts a human-readable English date/time string into a UNIX time tag.

Apply this function to convert a non-standardized date/time string into a standard, compatible UNIX time stamp.

Copy code The code is as follows:

// returns 13-Sep-05
echo date("d-M-y", strtotime("today"));
// returns 14-Sep-05
echo date("d-M-y", strtotime("tomorrow"));
// returns 16-Sep-05
echo date("d-M-y", strtotime("today +3 days"));
?>

strftime($ format,$ts)

As defined by the previous setlocale() function, this function formats the UNIX time stamp into a date string suitable for the current environment.

Apply this function to create a date string compatible with the current environment.

Copy code The code is as follows:

// set locale to France (on Windows)
setlocale(LC_TIME, "fra_fra");

// format month/day names
// as per locale setting
// returns "septembre" and "mardi"

echo strftime("Month: %B ");
echo strftime("Day: %A ");
?>

microtime( )

As defined by the previous setlocale() function, this function formats the UNIX time stamp into a date string suitable for the current environment.

Apply this function to create a date string compatible with the current environment.

Copy code The code is as follows:

// get starting value
$start = microtime();

// run some code
for ($x=0; $x$null = $x * $x;
}

// get ending value
$end = microtime();

// calculate time taken for code execution
echo "Elapsed time: " . ($ end - $start) ." sec";
?>

gmmktime($hour, $minute, $second, $month, $day, $year)

This function generates a UNIX time stamp from a series of date and time values ​​expressed in GMT time. When no arguments are used, it generates a UNIX time stamp of the current GMT time.

Use this function to obtain the UNIX time label of GMT real-time time.

Copy code The code is as follows:

// returns timestamp for 12:25 :23 9-Jul-2006
echo gmmktime(12,25,23,7,9,2006);
?>

gmdate($format, $ ts)

This function formats a UNIX time stamp into a human-readable date string. This date string is expressed in GMT (not local time).

This function is applied when the time label is expressed in GMT.

Copy code The code is as follows:

// format current date into GMT
// returns "13-Sep-2005 08:32 AM"
echo gmdate("d-M-Y h:i A", mktime());
?>

date_default_timezone_set($tz), date_default_timezone_get()

All date/time function calls after this function set and restore the default time zone.

Note: This function is only valid in PHP 5.1+.

This function is a convenient shortcut for setting the time zone for future time operations.

Copy code The code is as follows:

// set timezone to UTC
date_default_timezone_set('UTC');
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/319050.htmlTechArticlePHP’s date and time function date() 1, year-month-day copy code code is as follows: echo date(' Y-m-j'); 2007-02-6 echo date('y-n-j'); 07-2-6 Uppercase Y represents the four-digit year, while lowercase y represents the year...
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

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.

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

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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),