search
HomeBackend DevelopmentPHP Tutorialphp date and time_PHP tutorial

php date and time_PHP tutorial

Jul 13, 2016 pm 05:44 PM
phpsuperiorbuilt-infunctionanddeal withdevelopsupplydatetimeof

PHP provides a large number of built-in functions, which allows developers to manage time with ease and greatly improves work efficiency. Today we will introduce some common PHP date and time functions and date and time processing to students.

9.1 Commonly used date and time processing functions

Table 9-1: Commonly used date and time processing functions

Function

Say Ming

checkdate

Verify the time function to determine whether the time is valid, return true if valid, otherwise return false

date_default_timezone_get

Get the default time zone used by script datetime functions

date_default_timezone_set

Set the default time zone for date and time functions

date

Format a local time/date

getdate

Get date/time information

gettimeofday

Get current time

localtime

Get local time

microtime

Returns the current timestamp and microseconds

mktime

Get a UNIX timestamp

strtotime

Parse any English text datetime description into a UNIX timestamp

time

Returns the current UNIX timestamp

9.2 Processing date and time

9.2.1 Get the current date and time: date() function, usage:

date(string format,int timestamp)

This function will return a string generated by the timestamp parameter according to the specified format. The parameter timestamp is optional. If omitted, the current time is used. The format parameter allows developers to output the time and date in the format they specify.

date_default_timezone_set(PRC); //Set Beijing time.

1. Year-month-day

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

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

An uppercase Y represents a four-digit year, while a lowercase y represents a two-digit year;

Lowercase m represents the number of the month (with a leading), while lowercase n represents the number of the month without the leading.

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

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

Uppercase M represents the 3 abbreviated characters of the month, while lowercase m represents the number of the month (with leading 0);

There is no uppercase J, only lowercase j represents the day of the month, without the leading o; if a leading month is required, use a lowercase d.

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

echo date('Y-F-jS'); //Example: 2007-February-6

Capital M represents the 3 abbreviated characters of the month, while capital F represents the full English letter of the month. (no lowercase f)

Capital S represents the suffix of the date, such as "st", "nd", "rd" and "th", depending on the date number.

Summary:

The year can be represented by uppercase Y and lowercase y;

Months can be represented by uppercase F, uppercase M, lowercase m and lowercase n (two ways to represent characters and numbers respectively);

Lowercase d and lowercase j can be used to represent the day, and uppercase S represents the suffix of the date.

2. Hour:minute:second

By default, PHP interprets the displayed time as "Greenwich Mean Time", which is 8 hours different from our local time.

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

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

A lowercase g indicates a 12-hour clock without leading 0s, while a lowercase h indicates a 12-hour clock with leading 0s.

When using the 12-hour clock, it is necessary to indicate morning and afternoon. Lowercase a represents lowercase "am" and "pm", and uppercase A represents uppercase "AM" and "PM".

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 hour in 24-hour format with leading

Summary:

The letter g represents the hour without leading, and the letter h represents the hour with leading;

Lowercase g and h represent the 12-hour format, while uppercase G and H represent the 24-hour format.

3. Leap year, week, day

Capital L indicates whether this year is a leap year, Boolean value, returns 1 if true, otherwise 0;

The lowercase l represents the full English word for the day of the week (Tuesday);

Instead, use a capital D to represent the 3-character abbreviation of the day of the week (Tue).

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

echo date('W'); //Example: This week is the 06th week of the year

The lowercase w represents the day of the week, and the numeric form represents

Capital W represents the number of weeks in the year

echo date('t'); //Example: This month has 28 days

echo date('z'); //Example: Today is the 36th day of this year

Lowercase t represents the number of days in the current month

Lowercase z indicates what day of the year today is

4. Others

echo date('T'); //Example: UTC

A capital T represents the server’s time locale

echo date('I'); //Example: 0

Capital I means to determine whether the current daylight saving time is, if true, return 1, otherwise 0

echo date('U'); //Example: 1170769424

A capital U represents the total number of seconds from January 1, 1970 to the present, which is the UNIX timestamp of the Unix time epoch.

echo date('c'); //Example: 2007-02-06T14:24:43+00:00

Lowercase c represents an ISO8601 date, the date format is YYYY-MM-DD, the letter T is used 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'); //Example: Tue, 06 Feb 2007 14:25:52 +0000

A lowercase r indicates the RFC822 date.

9.2.2 Obtain date information: getdate() function

Syntax:

Array getdate(int timestamp)

This function returns date and time information in the form of an array. If there is no timestamp, the current time shall prevail. The description of the associative array elements returned by this function is shown in Table 9-2:

Table 9-2: Description of associative array elements returned by the getdate() function

Element

Say Ming

seconds

Seconds, return value 0~59

minutes

Minutes, the return value is 0~59

hours

Hours, the return value is 0~23

mday

The day of the month, the return value is 1~31

wday

The day of the week, the return value is 0 (Sunday) ~ 6 (Saturday)

mon

Month number, return value is 1~12

year

The complete year represented by 4 digits, return value plus 2000 or 2008

yday

The day of the year, return value 0~365

weekday

The complete text representation of the day of the week, the return value is Sunday~Saturday

month

The complete text representation of the month, the return value is January~December

0

Returns the number of seconds since the UNIX epoch

Example:

$arr = getdate();

echo $arr[year]."-".$arr[mon]."-".$arr[mday]."";

echo $arr[hours].":".$arr[minutes].":".$arr[seconds]."".$arr[weekday];

echo "

";

echo "Today is the $arr[yday]th of year";

?>

Effect:

9.3 UNIX timestamp

The timestamp is the creation, modification, and access time in the file attributes. Digital time stamp service (DTS) is one of the web website security services that can provide security protection for the date and time information of electronic files.

9.3.1 What is timestamp

The timestamp is an encrypted credential document, which consists of 3 parts:

² Files that need to be timestamped are encrypted using Hash encoding to form a summary.

² DTS accepts the date and time information of the file.

² Encrypt received DTS files.

The digital time is added by the certification unit DTS, based on the time when DTS receives the file.

The working principle of timestamp is to convert the time value into an encrypted value through other encryption methods. When the time changes, the encrypted value also changes.

The advantage of the timestamp is that the changing encrypted value prevents the value from being stolen and illegally reused, which also plays the role of encryption. Timestamps mainly rely on time and generate a unique value within an agreed period of time.

9.3.2 Get local timestamp: mktime() function

Syntax:

int mktime(int hour, int minute, int month, int day, int year, int [is_dst])

Table 9-3: Parameter description of mktime() function

Parameter

Say Ming

hour

Hours

minute

Minutes

second

Number of seconds (within one minute)

month

Number of months

day

Number of days

year

Year number

is_dst

The parameter is_dst can be set to 1 during daylight saving time, or 0 if not; if not sure whether it is daylight saving time, set to -1 (default value)

Note: The typical range of valid timestamps is December 13, 1901 20:45:54 GMT to January 19, 2038 03:13:07 (this range conforms to the minimum and maximum values ​​​​of 32-bit signed integers) . In Windows systems, this range is limited to January 1, 1970 to January 19, 2038.

Example:

echo "The timestamp returned by the mktime function:".mktime()."

";

echo "The current date is:".date("Y-m-d",mktime())."

";

echo "The current time is:".date("H:i:s",mktime());

?>

Effect:

9.4 System time zone setting

During the learning process, many students found that the time obtained through the date() function is different from the local time. This is because PHP5 has rewritten the date() function. Therefore, the current date and time function is 8 hours less than the system time. . The default setting in the PHP language is standard Greenwich Time (that is, the zero time zone is used).

There are two main ways to change the time zone setting in PHP language:

1. Modify the settings in the php.ini file, find the;date.timezone = option under [date], change this item to date.timezone=Asia/Hong_Kong, and then restart the apache server.

2. In the application, add the following function before using the time and date function:

date_default_timezone_set(“Asia/Hong_Kong”);

After the setting is completed, the date() function can be used normally, and the time difference problem will no longer occur.

9.5 Date and time problems encountered in time development

9.5.1 Compare the size of two times

In actual development, we often encounter the problem of judging the size of two times. Times in PHP cannot be directly compared. Therefore, first output the time in timestamp format, and then compare. This is a commonly used method.

There are two functions that can achieve this function. The strtotime() function is used here, which can parse the date and time description of any English text into a UNIX timestamp. The syntax of this function is:

int strtotime(string time, int now)

This function has two parameters. If the format of the parameter time is an absolute time, the now parameter has no effect; if the format of the parameter time is a relative time, then the corresponding time is provided by the parameter now. If the parameter now is not provided, the corresponding time is the current time. If parsing fails, -1.

is returned

Example:

$time1 = date("Y-m-d H:i:s"); //Get the current time

$time2 = "2008-2-3 16:30:00"; //Set a time for variable $time2

echo "The time of variable/$time1 is: ".$time1."
"; //Output two time variables

echo "The time of variable/$time2 is: ".$time2."
";

If (strtotime($time1)-strtotime($time2)

              echo "/$time1 is earlier than /$time2";       //If time1-time2

}else{

             echo "/$time2 is earlier than /$time1"; // Otherwise, it means that time2 is earlier

}

?>

Effect:

9.5.2 Calculate the difference between two dates

In addition to comparing the size of two dates, the strtotime() function can also accurately know the difference between two dates. The following uses a small countdown program to explain to students how to use the strtotime() function to calculate the difference between two dates.

$time1 = strtotime(date( "Y-m-d H:i:s"));

$time2 = strtotime("2008-2-3 17:10:00");

$time3 = strtotime("2008-8-8");

$sub1 = ceil(($time2 - $time1) / 3600); $sub1 = ceil(($time2 - $time1) / 3600); //60 * 60

$sub2 = ceil(($time3 - $time1) / 86400); //60 * 60 * 24

echo "There are still $sub1 hours before the holiday!!!" ;

echo "

";

echo "There are still $sub2 days until the opening of the Beijing Olympics!!!";

?>

Effect:

9.5.3 Calculate the running time of the page script

When browsing websites, search engines are often used. When searching for information, careful users will find that at the bottom of the search results, there is usually the words "Search time is...seconds".

The microtime() function is used here, which returns the current UNIX timestamp and microseconds. Returns a string in the format msec sec, where sec is the current UNIX timestamp and msec is the number of microseconds. The format of this function is:

string microtime(void)

                                                  Let’s calculate the running time of the above example, the code is as follows:

function run_time()

{

List($msec, $sec) = explode(" ", microtime());

Return ((float)$msec + (float)$sec);

}

$start_time = run_time();

$time1 = strtotime(date( "Y-m-d H:i:s"));

$time2 = strtotime("2008-2-3 17:10:00");

$time3 = strtotime("2008-8-8");

$sub1 = ceil(($time2 - $time1) / 3600); $sub1 = ceil(($time2 - $time1) / 3600); //60 * 60

$sub2 = ceil(($time3 - $time1) / 86400); //60 * 60 * 24

echo "There are still $sub1 hours before the holiday!!!" ;

echo "

";

echo "There are still $sub2 days until the opening of the Beijing Olympics!!!";

$end_time = run_time();

?>

The example runs in seconds

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/478726.htmlTechArticlePHP provides a large number of built-in functions, allowing developers to handle time with ease and greatly improving work efficiency. Today we will introduce some common PHP date and time letters to students...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor