Bagaimana untuk Menambah Minit pada Objek Masa Tarikh dalam PHP?

Mary-Kate Olsen
Lepaskan: 2024-11-15 04:19:02
asal
537 orang telah melayarinya

How to Add Minutes to a Date Time Object in PHP?

Adding Minutes to a Date Time in PHP: A Comprehensive Solution

Question: How can I increment a date time object in PHP by a specified number of minutes while preserving the original format?

Answer:

To effectively add minutes to a date time in PHP, we will employ a combination of the DateTime and DateInterval classes. Here's a detailed breakdown:

$minutes_to_add = 5;

$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));

$stamp = $time->format('Y-m-d H:i');
Salin selepas log masuk

Explanation:

  1. Instantiating a DateTime Object: We create a DateTime object using the 'new DateTime()' syntax. The parameter passed to it represents the initial date and time.
  2. Creating a DateInterval Object: This class is used to specify the duration to be added to the date time. In our case, 'PT' stands for a period of time, followed by the number of minutes ('5' in this example) and the letter 'M' to indicate minutes.
  3. Adding Duration to Date: The add() method is then used to add the specified duration to the DateTime object.
  4. Formatting the Output: Finally, the format() method returns the date and time in the desired format, preserving the original 'year-month-day hour:minute' structure.

The ISO 8601 standard for duration follows a specific string format. Here, 'P{y}Y{m1}M{d}DT{h}H{m2}M{s}S' represents a duration with various components, such as years ('Y'), months ('M'), days ('D'), hours ('H'), minutes ('M'), and seconds ('S'). In our case, we utilize 'PT5M' to indicate adding 5 minutes to the date time.

Atas ialah kandungan terperinci Bagaimana untuk Menambah Minit pada Objek Masa Tarikh dalam PHP?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan