search
HomeBackend DevelopmentPHP TutorialPHP Notes: Introduction to the use of date functions_PHP Tutorial

PHP Notes: Introduction to the use of date functions_PHP Tutorial

Jul 21, 2016 pm 03:11 PM
phpintroduceusefunctionitpowerfuldateyesmostofnoteslanguage

Introduction

PHP is a very amazing language. It is powerful enough (the core language of the largest blog (WordPress)), it is widespread enough (runs on Facebook, the largest social networking site), and it is simple enough (as the preferred introductory language for beginners). Works well on low-cost machines. Moreover, the PHP language has many very good server packages (such as WAMP and MAMP), which are very convenient to install on your machine. PHP has very rich library resources, making it easy for developers to handle some businesses. Since we have the most contact with dates in the project, we will start learning from the date function today.

Give a simple date example

I will use the echo command to output the content to our client (browser). I will use the following code as the base code.

Copy code The code is as follows:




Getting started with dates in php5


date_default_timezone_set('Asia/Shanghai');
echo "Today is ",date('l');
?>



You will see the following content in your browser.

Today is Friday This function outputs the text format of the day of the week. The date function requires at least one character parameter (this parameter tells us how to format the current date).

Try different formats

If you look at the PHP date function in the php manual, you will find that there are many ways to format dates.



will get

Today is 2012-08-17

Some dates are commonly used, so PHP provides some constants for you to use. For example, you can use cookies to get the client date.

You will get the following content

Today is Friday, 17-Aug-12 11:34:38 ​​CST Be careful not to use quotation marks when using constants.


What time is it now?

If you want to output the current time, you can use date (different formatting character parameters).

You will get

The time is 11:39:59am

Localize your time zone

If you find that the above code does not give the correct time, it is most likely because your server is set to a different time zone than your local time zone. You need to specify the time zone on the server, then you use the following code:



This will set the Shanghai time zone in China. This is a function of php5 (note older versions of php), there are many for you to choose the time zone. If you want it to be permanent, you can modify your php.ini file.

Get other times

You often need other times, not the current time. When you create a time using the date() function, the system uses Unix system time. This time represents the number of seconds since January 1, 1970 00:00:00 GMT (Unix Epoch Time) until now.

To specify how to get the date at a specified time, you can provide the number of seconds as the second parameter of the date(0 function.

The result is:

Today is 2011-06-27

This may seem useless, but it means you can use the date() function to do calculations. Before doing this, you need to simply create a timestamp.

Creating timestamps

There are many ways to create timestamps. We can use the mktime() function to get the timestamp we need.

Copy code The code is as follows:

$mytime=mktime(9, 23, 33, 6, 26, 2011);
echo "Today is ",date('Y-m-d g:i:sa', $mytime);
?>

The result is :

Today is 2011-06-26 9:23:33am mktime()

The function requires you to pass hours, minutes, seconds, months, days, and years in sequence. This is a good way to get a timestamp, but there are cooler ways.

Get the timestamp through characters

You can use the strtotime() function to get the timestamp, and PHP converts readable characters into Unix timestamps. PHP is quite flexible in converting characters into timestamps, so you can plug in all kinds of values ​​to get the timestamp you want.

This is a simple example:

Copy the code The code is as follows:

$mytime=strtotime("7:50pm June 26 2011");
echo "Today is ",date('Y-m-d g:i:sa', $mytime );
?>

Output:

Today is 2011-06-26 7:50:00pm

PHP is pretty slick at interpreting characters, but it's not perfect, so be sure to test the characters you enter before you insert them. Use "english-like instructions" to convert the required timestamp, which is a very good way. You can do it like this:

Copy the code The code is as follows:

$nextfriday=strtotime("next Friday"); //Next Friday
$nextmonth=strtotime("+1 Month"); //Calculate the time one month from today
$lastchristmas=strtotime("-1 year dec 25"); // Last Christmas

Get the date range

The value returned by strtotime is converted to a number. We can do basic operations with these numbers. We can use these numbers. Doing a lot of very interesting things. For example, you need to teach a subject every Tuesday for 16 weeks, and you want to get your teaching time. You can do the following things.
Copy code The code is as follows:

$startdate = strtotime('next Tuesday');
$enddate = strtotime('+16 weeks', $startdate);
$currentdate = $startdate;
echo '
    ';
    while($currentdate echo "t
  1. ", date('M d', $currentdate);
    $currentdate = strtotime('+1 week', $currentdate);
    endwhile;
    echo '
';
?>

You will get the following results:
Copy code The code is as follows:

Aug 21
Aug 28
Sep 04
Sep 11
Sep 18
Sep 25
Oct 02
Oct 09
Oct 16
Oct 23
Oct 30
Nov 06
Nov 13
Nov 20
Nov 27
Dec 04

Note Look at this line: $currentdate = strtotime("+1 week", $currentdate). In this line, you will find that you need to specify a timestamp as the second parameter. strtotime will use this parameter instead of the default timestamp (today) and perform the operation.

Number of days to a certain date

When using the calculator, we will try to calculate the number of days to a certain day. You can easily calculate the timestamp of the fourth Thursday in November.

Copy code The code is as follows:

$someday = strtotime("3 weeks thursday November 1");
$ daysUtilDate = ceil(($someday - time())/60/60/24);
echo "There are ", $daysUtilDate, " until Thanksgiving";

First, let’s start Calculate the date of Thanksgiving (the third Thursday after the first Thursday after November 1), and then we use simple arithmetic to calculate the number of days between Thanksgiving and the current time. When we perform comparison operations, we can use time() because it returns the number of seconds since the epoch of the current time.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326804.htmlTechArticleIntroduction PHP is a very amazing language. It is powerful enough (the core language of the largest blog (wordpress)), it is broad enough (running on the largest social networking site facebook), it is enough...
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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

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

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)