Home Backend Development PHP Tutorial Tutorial on Date function and timestamp function in PHP and format conversion between them (with examples)

Tutorial on Date function and timestamp function in PHP and format conversion between them (with examples)

Jun 08, 2020 am 11:30 AM
date function

Tutorial on Date function and timestamp function in PHP and format conversion between them (with examples)

Date function and timestamp function in php and format conversion tutorial between them (with examples)

In In PHP website development and construction, dates and times often need to be processed. PHP provides a variety of date and time functions to facilitate PHP developers to calculate and format dates and times.

It is very necessary to master PHP date functions, and it also lays the foundation for processing the format conversion between PHP date functions and Mysql database dates.

As the opening tutorial on PHP date functions, I use a PHP example tutorial to introduce the PHP basic date function date and Unix timestamp function as well as the conversion methods of date formats between each other.

1. PHP date and time zone setting

Before enabling the PHP date function, you first need to ensure that the set time zone is correct, otherwise the displayed date may be There are discrepancies. When setting up the PHP environment, you only need to set date.timezone to the corresponding time zone in the PHP.INI configuration file.

If you do not have the right to operate the PHP.INI configuration file, you can obtain the time zone of the current PHP running environment through the PHP time zone function date_default_timezone_get(void).

Use the date_default_timezone_set(string $timezone_identifier) ​​function to set the corresponding time zone.

For more time zones supported by PHP, please check http://www.php.net/manual/en/timezones.php.

2. PHP format date function Date

Prototype string date(string $format[,int $timestamp])

$format - PHP The format code of the date function date

$timestamp - Unix timestamp, the default is the current timestamp (optional)

3. Format characters ————- Description ———— The return value is described as follows:

Day

d——The day of the month, returns 2 digits —— 01 to 31

j —— The day of the month, 1 to 9 without zero —— 1 to 31

S —— The English suffix of the number of days in the month —— 2 characters st, nd, rd or th. Can be used with j

z —— The day of the year —— 0 to 366

Week

 l——Day of the week——Sunday to Saturday

 D——English day of the week, text representation——3 letters Mon to Sun

 N——Number representing the day of the week (New in PHP 5.1.0) - 1 (Monday) to 7 (Sunday)

w - Day of the week - 0 (Sunday) to 6 (Saturday)

 W - The week number in the year in ISO-8601 format, each week starts on Monday (newly added in PHP 4.1.0) - 42 (the 42nd week of the year)

month(Month)

 F —— month —— January or March January to December

 m —— month represented by numbers —— 01 to 12

M —— The month represented by the three-letter abbreviation —— Jan to Dec

 n —— The month represented by the number —— 1 to 12

t — – Number of days in the month —— 28 to 31 Is 1, otherwise it is 0

 o —— ISO-8601 format year number. Similar to Y , unless the ISO week number (W) belongs to the previous or next year, that year is used. (New in PHP 5.1.0) —— 1999 or 2003 Y —— The year represented by four digits —— 1999 or 2003 y —— The year represented by two digits —— — 99 or 03

Time (Time)

 a —— Morning and afternoon —— am or pm

 A —— Morning and Afternoon —— AM or PM  B —— Swatch Internet Time —— 000 to 999  g —— Hour, 12-hour format —— No leading zero 1 to 12

G —— Hour, 24-hour format —— No leading zero 0 to 23

h —— Hour, 12-hour format —— With leading zero 01 to 12

H —— Hours, 24-hour format —— With leading zeros 00 to 23

i —— Minutes —— 00 to 59

s —— Seconds —— 00 to 59

Timezone

 e - Time zone identifier (newly added in PHP 5.1.0) - UTC, GMT, Atlantic/Azores

I —— Whether it is daylight saving time —— Summer time is 1, otherwise it is 0

T —— Time zone abbreviation —— For example: EST, MDT

Z —— With the current time zone Time zone difference, in seconds —— -43200 to 43200

Full Date/Time (Full Date/Time)

 c — — Date in ISO 8601 format (new in PHP 5) — 2004-02-12T15:19:21 00:00

 r — Date in RFC 822 format — Thu, 21 Dec 2000 16:01 :07 0200

U - General description from 1970 1.1 to a certain moment, that is, Unix timestamp, see time()

For the English documentation of PHP date function date formatting characters, please refer to http ://www.php.net/manual/en/function.date.php

Date function usage tips: When using the PHP date function date to output a formatted date format, you You can first write out the date format you need to output, and then use the formatting characters in the date function to combine it. It will be very easy to use.

4. Use the PHP date function date to convert the Unix timestamp format.

The second optional parameter $timestamp of the PHP date date function is based on the Unix timestamp. The form exists, and this parameter can be used to convert the Unix timestamp into the corresponding date format. Using Unix timestamp has many benefits in parameter passing, date calculation, etc. It is convenient and concise.

Commonly used functions in PHP to convert dates into Unix timestamps mainly include mktime, time, strtotime. PHP date function mktime is mainly used to convert date and time into Unix timestamp format.

The prototype is as follows

int mktime ([int $hour = date("H")[,int $minute = date("i")[,int $second = date("s")[,int $month = date("n")[,int $day = date("j")[,int $year = date("Y")[,int $is_dst = -1 ]]]]]]])
Copy after login

mktimeAll parameters of the function are optional, where $is_dst indicates whether it is daylight saving time, when the mktime function parameters are all When empty, it will default to the current time, similar to the time function.

PHP date functiontime is mainly used to obtain the current time, which exists in Unix timestamp format. PHP date function strtotime is mainly used to convert the date and time described in English into a Unix timestamp.

The prototype is as follows

int strtotime(string $time[,int $now])
Copy after login

$time parameter mainly exists in the form of English text description.

The $now optional parameter mainly represents a basis for $time to calculate date and time. The default is the current Unix timestamp.

PHP date date function is mainly used to convert and output various date formats. If you want to obtain various parts of the date and time, you can obtain it by passing the Unix timestamp parameter to the getdate function, getdate The function will return a related array with the following array key values:

Seconds —- Number of seconds
Minutes —- Minutes
Hours —- Hour
mday —- Day of the month
 wday —- Day of the week, 0 (for Sunday) to 6 (for Saturday)
mon —- Month
Year —- The complete year represented by four digits
yday —- The day of the year Day
Weekday —- The textual representation of the week, Sunday to Saturday
Month — The textual representation of the month, January to December
0 —- The number of seconds since the Unix epoch, and the return value of time() similar.

Various date format conversion, calculation and output can be performed through the above PHP Unix timestamp functions and the PHP date function.

5. PHP date calculation example

Calculate age

<?php
    $day = 1;
    $month = 1;
    $year = 1989;
   
    $birthday = mktime(0,0,0,$month,$day,$year);
   
    $nowunix = time();
   
    $age = $nowunix - $birthday;
   
    $age = floor($age / (365*24*60*60));
   
    echo $age;
?>
Copy after login

Date addition Subtraction

<?php
    $nowUnix = time();
   
    $addTime = $nowUnix + (24*60*60); //日期加一天
   
    $redTime = $nowUnix - (24*60*60);//日期减一天
   
    echo date("Y-m-j",$addTime);
    echo date("Y-m-j",$redTime);
?>
Copy after login

6. Example of strtotime date calculation and format conversion

Date addition and subtraction can also be completed through the strtotime function

<?php
    $nowTime = strtotime("now");
    echo date("Y-m-j",$nowTime)."<br/>";
   
    $nowTime = strtotime("10 September 2010");
    echo date("Y-m-j",$nowTime)."<br/>";
   
    $nowTime = strtotime("+1 day");
    echo date("Y-m-j",$nowTime)."<br/>";
   
    $nowTime = strtotime("+1 week");
    echo date("Y-m-j",$nowTime)."<br/>";
   
    $nowTime = strtotime("+1 week 2 days 4 hours 2 seconds");
    echo date("Y-m-j",$nowTime)."<br/>";
   
    $nowTime = strtotime("next Thursday");
    echo date("Y-m-j",$nowTime)."<br/>";
   
    $nowTime = strtotime("last Monday");
    echo date("Y-m-j",$nowTime)."<br/>";
?>
Copy after login

This completes the introduction to the meaning of date formatting characters in the PHP date function, the introduction of some PHP Unix timestamp functions, and examples of conversion and formatted output between them. This is useful for mastering the calculation and conversion of PHP date and time functions. is very necessary. I hope it will be helpful to those who are starting to learn PHP.

Recommended tutorial: "PHP Video Tutorial"

The above is the detailed content of Tutorial on Date function and timestamp function in PHP and format conversion between them (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles