search
HomeBackend DevelopmentPHP TutorialPHP date and time application eight: add or subtract the number of days from a specific date

In this article "PHP date and time application seven: Get the date and day of the week in a certain country", I introduced to you how to get the date and day of the week in a certain country; continue the date and time today Using the series of exercises~

The topic of this article is "How to write a PHP script to add/subtract the number of days from a specific date".

To put it simply, let us use PHP to output the date how many days ago and how many days after.

If you still don’t understand, let’s look at the code directly:

The PHP code is as follows:

<?php

$dt=&#39;2021-09-15&#39;;
echo &#39;原始日期 : &#39;.$dt."<br>";
$no_days = 50;
$bdate = strtotime("-".$no_days." days", strtotime($dt));
$adate = strtotime("+".$no_days." days", strtotime($dt));
echo &#39;50天前 : &#39;.date("Y-m-d", $bdate)."<br>";
echo &#39;50天后 : &#39;.date("Y-m-d", $adate)."<br>";

The output result is:

PHP date and time application eight: add or subtract the number of days from a specific date

Now you understand!

In the above code, we gave a specified date "2021-09-15", and then specified a number of days "50".

Finally, use the -, operator to find the date 50 days before and 50 days after the date.

Of course there are two important functions that everyone needs to master, namely strtotime and date:

strtotime()The function of the function is to Any English text date or time description is resolved to a Unix timestamp (number of seconds since January 1 1970 00:00:00 GMT).

Note:

For dates in m/d/y or d-m-y format, if the separator is a slash (/), the American m/d/y format is used. If the delimiter is a dash (-) or a dot (.), the European d-m-y format is used. To avoid potential errors, you should use YYYY-MM-DD format whenever possible or use the date_create_from_format() function.

date()The function is to format the local date and time and return the formatted date string.

Note:

PHP 5.1.0: Added E_STRICT and E_NOTICE time zone errors. The valid range of timestamps is from Friday, December 13, 1901 20:45:54 GMT to January 2038. Tuesday, 19 May 03:14:07 GMT In versions prior to 5.1.0, on some systems (such as Windows) timestamps were limited to from 01-01-1970 to 19-01-2038.

PHP 5.1.1: Added standard date/time format constants for specifying format parameters.

Finally, I would like to recommend the latest and most comprehensive "PHP Video Tutorial"~ Come and learn!

The above is the detailed content of PHP date and time application eight: add or subtract the number of days from a specific date. For more information, please follow other related articles on the PHP Chinese website!

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
Where to declare a php function?Where to declare a php function?Jul 23, 2025 am 04:25 AM

Declaring the location of a function in PHP is important because it affects the availability of the function. 1. Functions are most commonly declared in .php files and loaded through include or require when needed; 2. They can be placed on the top of the script or in a dedicated function file, as long as they are defined before calling, it is recommended to centrally manage to improve maintenance; 3. In object-oriented programming, functions can be declared as class methods or in namespace to avoid naming conflicts; 4. The same function cannot be declared repeatedly, and conflicts can be avoided through include_once, require_once or function_exists checks. Ensuring that the function is defined before being called and only once is the key to handling function declarations in PHP.

Do Comments Slow Down PHP?Do Comments Slow Down PHP?Jul 23, 2025 am 04:24 AM

PHP ignores the execution overhead of comments, because comments are discarded during the compilation stage and will not enter the opcode execution process; 2. The only negligible performance impact is the microsecond parsing time when the script is first loaded, and there is almost no impact after OPcache is enabled; 3. Priority should be paid to the real performance bottlenecks such as database queries and loops, rather than the number of comments.

Understanding PHPDoc TagsUnderstanding PHPDoc TagsJul 23, 2025 am 04:24 AM

PHPDoctagsarestructuredannotationsthatdocumentcodeforbetterunderstandingandtoolingsupport;1)@paramdescribesfunctionparameterswithtypeanddescription,2)@returnspecifiesthereturntypeandmeaning,3)@throwsindicatespossibleexceptions,andtogethertheyenhanceI

What are some best practices for naming PHP functions?What are some best practices for naming PHP functions?Jul 23, 2025 am 04:23 AM

In PHP development, function naming should start with a verb to maintain consistency, avoid blurred names, and control length. 1. Use clear verbs such as get, set, calculate, etc. to express behavioral intentions; 2. Use is, has, get and other prefixes for the return value; 3. Follow the project specifications, recommend camelCase to avoid confusing naming style; 4. Avoid abbreviation and vague names, and use complete words to improve readability; 5. The length of the function name is moderate, and it is recommended to be controlled within 3 to 5 words. Too long may require splitting responsibilities.

What are some common mistakes when working with PHP functions?What are some common mistakes when working with PHP functions?Jul 23, 2025 am 04:23 AM

Common function usage errors in PHP development include: 1. Ignore the return value type and error handling, and check the return value and use strict comparison; 2. If the parameter order is wrong or the type does not match, you should consult the document and enable the type declaration; 3. Ignore the difference between reference passing and value passing, and confirm whether the original variable will be modified before use; 4. Confuse variadic function parameters and default parameters, and put the default parameters at the end and verify the variadic parameters.

How to define a php function with optional parameters?How to define a php function with optional parameters?Jul 23, 2025 am 04:23 AM

Defining functions with optional parameters in PHP can be implemented through parameter default values. 1. Specify the default value for the parameter when defining the function. If it is not passed in during the call, the default value is used. Parameters with default values must be placed after the parameter without default value; 2. Default values can be set separately by multiple optional parameters. Parameters must be passed in sequence when calling, and intermediate parameters cannot be skipped; 3. When there are many parameters, parameters can be passed in arrays, and the default values and incoming values can be combined to improve flexibility and maintainability.

php function to trim whitespace from a stringphp function to trim whitespace from a stringJul 23, 2025 am 04:22 AM

In PHP, the trim() function can remove whitespace characters at both ends of the string. If you need to remove non-whitespace characters, you can specify it through the second parameter. When only one-sided whitespace is removed, ltrim() or rtrim() can be used. To remove excess whitespace inside the string, you need to combine regular expressions to use the preg_replace() function. trim() removes spaces, tabs, newlines and empty bytes by default, and does not affect the content in the middle of the string. ltrim() is used to remove the left blank, rtrim() is used to remove the right blank, and the regular expression '/\s /' can match any consecutive whitespace characters and replace them with a single space to achieve internal whitespace cleaning.

What is a variadic php function?What is a variadic php function?Jul 23, 2025 am 04:22 AM

The way to define mutable parameter functions in PHP is to use the... operator, which allows the function to accept any number of parameters. 1. Add... before function parameters, such as functionsum(...$numbers), and the parameters will be stored in an array. 2. Variable parameter functions are suitable for mathematical operations, string splicing, routing or event processing scenarios. 3. For versions before PHP5.6, variadic parameter behavior can be simulated through func_get_args(), func_num_args() and func_get_arg(). For example logMessages("Userloggedin","Sessio

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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