Home Backend Development PHP Tutorial PHP date processing function_PHP tutorial

PHP date processing function_PHP tutorial

Jul 21, 2016 pm 02:53 PM
php content function Include and deal with How many Change Way date time show of at present

This article contains the following content:
1. Get the current date and time - how many ways do we have?
2. Change the way the date is displayed - the display form of date and time
3. Convert the current date to Unix timestamp value
4. Change date
a. Add time
b. Subtract time
c. Find the interval between two dates
5. Add DateAdd function to PHP
6. Add DateDiff function to PHP

** Get the current date and time

In Unix, time is expressed by calculating the number of seconds that have passed since 0:00 on January 1, 1970. This is called a UNIX timestamp (Unix Epoch).
If we have a piece of code like this:

1. will return the value 958905820, and the time at this time is 12:43 on May 21, 2000.

You might say this is pretty good. When this doesn't help me at all, or only a little. In PHP, all date processing functions must use the timestamp value returned by time(). At the same time, since PHP uses the same timestamp value in both Unix and Windows systems, this allows you to port it between different systems without modifying the code. Another benefit is that the time() function returns an integer, which you can store in the database as an integer field or a text field without having to use a special date/time field.

Now that you have a basic understanding of Unix timestamp values, let’s show you what they are used for.

Change the way the date is displayed - the display format of date and time

PHP provides two methods to convert Unix timestamp values ​​into useful data. The first is the date() function. This function takes two parameters - the first string is used to set the format you wish to return, and the second is the Unix timestamp value.
Format strings use some simple special formatting characters to display the date and time in the format you want to see. Suppose you want the date to be displayed in the format "18h01 Sunday 21 May".
We need to use a special formatting character for each part of the string, which you can find in the date and time function library in the PHP manual. There are a lot of such special formatting characters. They represent the day of the week, the English name of the month, the year represented by 2 or 4 digits, whether it is morning (AM) or afternoon (PM) and others. The special characters we need for this example are:
‘H’ – hour in 24-hour format
‘i’ - minutes
‘l’ - the full English name of the day of the week
‘d’-the day of the month
‘F’ - the full English name of the month

So our format string is "Hhi l d F" and the PHP code is:

1. When we execute this code, we find that the result we get is: 180609 Sunday 21 May

This result looks a bit strange. Let's check the PHP manual again. It turns out that 'h' represents the hour in the 12-hour clock. This once again proves the truth: "The computer only does what you tell it to do, not what you want it to do." We have two options. The first one is to use the escape character "" before h: echo date ("Hhi l d F", time());

We get this result: 18h12 Sunday 21 May

This is exactly what we want. But if we need to include a date and time in a very complex sentence, do we need to use escape characters for each character? The answer is of course no. We use another function strftime().

strftime() has two benefits. The first benefit is beyond the scope of this article - if you use the setlocale() function, you can get the name of the month in the corresponding language through strftime. An additional benefit is that you can include special date and time formatting characters in your strings. This also means that whether or not you want to learn all the special formatting characters for the date() function, you have to learn a whole different set of formatting characters.

strftime() works no differently than date(), except that the special formatting character must be preceded by a percent sign %. If you use the strftime() function, the code of the previous example is as follows:

1. The result is: 18h24 Sunday 21 May

This may seem oversimplified, but think about it if you need to display "Today is Sunday 21 May 2000. The time is somewhere close to 18h24." I would definitely use the date() function It's annoying.
At the beginning, I mentioned that we have two ways to get useful data from Unix timestamp values. We just learned about date() and strftime(). Another getdate(). This function only requires a Unix timestamp value as a parameter, and the return value of the function is an array of date and time.
Here is an example:

1. The returned result is: Sunday

Except "weekday", the other parts of the array are:
"seconds" – seconds
"minutes" –minutes
"hours" – hours
"mday" - the day of the month
"wday" - day of the week (number)
"mon" - month (number)
"year" –year
"yday" - rThe day of the year (number)
"month" - the full name of the month
We can now get easily identifiable dates and times. What about others?

**Convert the current date to a Unix timestamp value

Usually you have to deal with data in some date or time format. Open an Access database of M$. All dates are stored in the format of YYYY/MM/DD. Adding the current date is 2000/05/27. The Mktime() function can convert a time into a Unix timestamp value.
The format of the function is: int mktime(int hour, int minute, int second, int month, int day, int year, int [is_dst] );

From left to right you must provide hours, minutes, seconds, months, days and years. The last parameter is used to specify whether you are in daylight saving time, this parameter is optional, so we will ignore it.

The code is as follows:

1. Since I don’t know that these parameters of hours, minutes and seconds must be filled in at the same time, I will It is set to 0. Setting to 0 means the time is midnight.

1.

1.
*Modification date

Sometimes we need to know when it is 6 hours later, the date 35 days ago or how many seconds have passed since you last played Quake 3. We already know how to get a Unix timestamp value from a separate date and time using the mktime() function. What should we do if we need a Unix timestamp value other than the current date and time? Here are some exercises to help illustrate what we will do next.

As seen earlier, mktime() takes the following parameters: hours, minutes, seconds, months, days, and years. Think about Section 2, the getdate() function can get these parameters for us.

1. It seems a little confusing. I'm going to use some variables to make the program above look easier to understand.

1. Now we will get the timestamp generated by getdate() The values ​​are put into corresponding named variables, so the code becomes relatively easy to read and understand. Now if we need to add 19 hours to the current time, we use $hours+19 instead of $hours in the mktime() function. mktime() will automatically move the time to the next day for us.

1. After running, we get:
14h58 Saturday 03 Jun
09h58 Sunday 04 Jun
~E after adding 19 hours
The same goes for reducing time - you just need to reduce the value of the corresponding variable.
Getting the difference between two different time values ​​is also very simple. All you need to do is convert the two time values ​​into Unix timestamp values ​​and then subtract the two. The difference between the two is the number of seconds between the two times. Other algorithms can quickly convert seconds to days, hours, minutes, and seconds.

** Add DateAdd function to PHP

As I said at the beginning of the article - the reason for writing this article is because I can't find an ASP-like DateDiff function in PHP. After introducing how PHP handles dates and times, let us transplant two functions commonly used in ASP to PHP. The first function is DateAdd.
According to Vbscript's documentation, the DateAdd(interval,number,date) function is defined as "Returns the date to which the specified time interval has been added."

Inetrval is a string expression representing the time interval to be added, such as minutes or days; number is a numerical expression representing the number of time intervals to be added; Date represents the date.
Interval (time interval string expression) can be any of the following values:
yyyy yearyear
q Quarter
m Month
y Day of year number of year
d Day
w WeekdayThe number of days in a week
ww Week of year
h Hour hour
n Minutes
s Second seconds
The functions of w, y and d are exactly the same, that is, add one day to the current date, q adds 3 months, and ww adds 7 days.

1. 我们可以将上面的代码保存为dateadd.inc文件,然后运行以下代码:

1. 我们将得到:
15h41 Saturday 03 Jun
16h31 Saturday 03 Jun
为PHP添加DateDiff函数
现在DateAdd已经完成,那么DateDiff呢?
根据文档,DateDiff(interval,date1,date2)函数的定义为“返回两个日期之间的时间间隔”。
Intervals参数的用法与DateAdd函数中的相同。出于避免过于复杂的考虑,我们决定忽略Vbscript中DateDiff函数中其它复杂的参数,即其两个可选的参数变量[firstdayofweek[, firstweekofyear]](它们用于决定星期中第一天是星期天还是星期一和一年中第一周的常数。而且我们只允许intervals有以下五个值:"w"(周)、"d"(天)、"h"(小时)、"n"(分钟) 和"s"(秒)。

Let's see what we can come up with: 下面的代码是我们所需要的:

1. 将上面的代码存为datediff.inc文件,然后运行下面的代码:

1. 如果一切顺利,你可以看到以下结果:
Current time: 16h23 Saturday 03 Jun
Time plus 50 minutes: 17h13 Saturday 03 Jun
Interval between two times: 50
如果你在Unix机器上运行PHP,你必须编译PHP支持BC高精度函数。你必须下载BC库,然后将其解压到PHP4的根目录下,重新编译PHP,编译时要加上--enable-bcmath的选项。(详细说明见PHP4中README.BCMATH)。PHP4的Windows版本则不需要做任何修补即可直接使用BC高精度函数。
现在你已经得到处理日期和时间的函数,剩下的就是如何将其运用到你的PHP程序中。

 


 

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/371382.htmlTechArticleThis article contains the following content: 1. Get the current date and time - how many ways do we have? 2. Change the way the date is displayed - the display format of date and time 3. Convert the current day...
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 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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles