- date_modify
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes
- date_add
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- Php datetime добавить час
- Add hours to a date and time using PHP.
- Adding hours onto a date and time using PHP’s date and time functions.
- Adding hours onto a date and time using PHP’s DateTime object.
- date_add
- Список параметров
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
date_modify
Alter the timestamp of a DateTime object by incrementing or decrementing in a format accepted by DateTimeImmutable::__construct() .
Parameters
Procedural style only: A DateTime object returned by date_create() . The function modifies this object.
A date/time string. Valid formats are explained in Date and Time Formats.
Return Values
Returns the modified DateTime object for method chaining or false on failure.
Examples
Example #1 DateTime::modify() example
$date = new DateTime ( ‘2006-12-12’ );
$date -> modify ( ‘+1 day’ );
echo $date -> format ( ‘Y-m-d’ );
?>?php
$date = date_create ( ‘2006-12-12’ );
date_modify ( $date , ‘+1 day’ );
echo date_format ( $date , ‘Y-m-d’ );
?>?php
The above examples will output:
Example #2 Beware when adding or subtracting months
$date -> modify ( ‘+1 month’ );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
$date -> modify ( ‘+1 month’ );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>
The above example will output:
See Also
- strtotime() — Parse about any English textual datetime description into a Unix timestamp
- DateTimeImmutable::modify() — Creates a new object with modified timestamp
- DateTime::add() — Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds
- DateTime::sub() — Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object
- DateTime::setDate() — Sets the date
- DateTime::setISODate() — Sets the ISO date
- DateTime::setTime() — Sets the time
- DateTime::setTimestamp() — Sets the date and time based on an Unix timestamp
User Contributed Notes
date_add
Прибавляет заданный объект DateInterval к объекту DateTime.
Список параметров
Только для процедурного стиля: Объект DateTime, возвращаемый date_create() . Функция изменяет этот объект.
Возвращаемые значения
Возвращает объект DateTime для применения в цепи методов или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования DateTime::add()
$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘P10D’ ));
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>?php
$date = date_create ( ‘2000-01-01’ );
date_add ( $date , date_interval_create_from_date_string ( ’10 days’ ));
echo date_format ( $date , ‘Y-m-d’ );
?>?php
Результат выполнения данных примеров:
Пример #2 Другие примеры с DateTime::add()
$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘PT10H30S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?php
$date = new DateTime ( ‘2000-01-01’ );
$date -> add (new DateInterval ( ‘P7Y5M4DT4H3M2S’ ));
echo $date -> format ( ‘Y-m-d H:i:s’ ) . «\n» ;
?>
Результат выполнения данного примера:
2000-01-01 10:00:30 2007-06-05 04:03:02
Пример #3 Будьте внимательны при добавлении месяцев
$date = new DateTime ( ‘2000-12-31’ );
$interval = new DateInterval ( ‘P1M’ );
?php
$date -> add ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
$date -> add ( $interval );
echo $date -> format ( ‘Y-m-d’ ) . «\n» ;
?>
Результат выполнения данного примера:
Примечания
При работе с PHP 5.2 в качестве альтернативы можно воспользоваться функцией DateTime::modify() .
Смотрите также
- DateTime::sub() — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime
- DateTime::diff() — Возвращает разницу между двумя DateTime объектами
- DateTime::modify() — Изменение временной метки
Php datetime добавить час
The following examples show some pitfalls of Date/Time arithmetic with regard to DST transitions and months having different numbers of days.
Example #1 DateTimeImmutable::add/sub add intervals which cover elapsed time
Adding PT24H over a DST transition will appear to add 23/25 hours (for most timezones).
$dt = new DateTimeImmutable ( «2015-11-01 00:00:00» , new DateTimeZone ( «America/New_York» ));
echo «Start: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
$dt = $dt -> add (new DateInterval ( «PT3H» ));
echo «End: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
?>?php
The above example will output:
Start: 2015-11-01 00:00:00 -04:00 End: 2015-11-01 02:00:00 -05:00
Example #2 DateTimeImmutable::modify and strtotime increment or decrement individual component values
Adding +24 hours over a DST transition will add exactly 24 hours as seen in the date/time string (unless the start or end time is on a transition point).
$dt = new DateTimeImmutable ( «2015-11-01 00:00:00» , new DateTimeZone ( «America/New_York» ));
echo «Start: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
$dt = $dt -> modify ( «+24 hours» );
echo «End: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
?>?php
The above example will output:
Start: 2015-11-01 00:00:00 -04:00 End: 2015-11-02 00:00:00 -05:00
Example #3 Adding or subtracting times can over- or underflow dates
Like where January 31st + 1 month will result in March 2nd (leap year) or 3rd (normal year).
echo «Normal year:\n» ; // February has 28 days
$dt = new DateTimeImmutable ( «2015-01-31 00:00:00» , new DateTimeZone ( «America/New_York» ));
echo «Start: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
$dt = $dt -> modify ( «+1 month» );
echo «End: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
?php
echo «Leap year:\n» ; // February has 29 days
$dt = new DateTimeImmutable ( «2016-01-31 00:00:00» , new DateTimeZone ( «America/New_York» ));
echo «Start: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
$dt = $dt -> modify ( «+1 month» );
echo «End: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
?>
The above example will output:
Normal year: Start: 2015-01-31 00:00:00 -05:00 End: 2015-03-03 00:00:00 -05:00 Leap year: Start: 2016-01-31 00:00:00 -05:00 End: 2016-03-02 00:00:00 -05:00
To get the last day of the next month (i.e. to prevent the overflow), the last day of format is available.
echo «Normal year:\n» ; // February has 28 days
$dt = new DateTimeImmutable ( «2015-01-31 00:00:00» , new DateTimeZone ( «America/New_York» ));
echo «Start: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
$dt = $dt -> modify ( «last day of next month» );
echo «End: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
?php
echo «Leap year:\n» ; // February has 29 days
$dt = new DateTimeImmutable ( «2016-01-31 00:00:00» , new DateTimeZone ( «America/New_York» ));
echo «Start: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
$dt = $dt -> modify ( «last day of next month» );
echo «End: » , $dt -> format ( «Y-m-d H:i:s P» ), PHP_EOL ;
?>
The above example will output:
Normal year: Start: 2015-01-31 00:00:00 -05:00 End: 2015-02-28 00:00:00 -05:00 Leap year: Start: 2016-01-31 00:00:00 -05:00 End: 2016-02-29 00:00:00 -05:00
Add hours to a date and time using PHP.
This is a tutorial on how to add hours to a date and time using PHP.
In this guide, we will provide examples using both the regular date and time functions, as well as PHP’s DateTime object.
Adding hours onto a date and time using PHP’s date and time functions.
Take a look at the following example, which is intentionally verbose:
//Get the current time in Unix. $currentTime = time(); //The amount of hours that you want to add. $hoursToAdd = 2; //Convert the hours into seconds. $secondsToAdd = $hoursToAdd * (60 * 60); //Add the seconds onto the current Unix timestamp. $newTime = $currentTime + $secondsToAdd; //Print it out in a format that suits you. echo date("d/m/y H:i", $newTime), '
'; //Or try this. echo "$hoursToAdd hour(s) added onto " . date("d/m/y H:i", $currentTime) . " becomes " . date("d/m/y H:i", $newTime);
- Got the current Unix timestamp using PHP’s time function.
- Defined a variable called $hoursToAdd, which contains the number of hours that we want to add onto our date and time. In this case, we will be adding 2 hours to the current time. If we wanted to add 12 hours to the current time, then we would simply change this variable to 12.
- We then converted our hours into seconds by multiplying the number of hours by 3600 (60 x 60 = 3600). This works because there are 3600 seconds in one hour. In the case above, 2 is multiplied by 3600, which gives us 7200. This is correct, as there are 7200 seconds in two hours.
- We then added these seconds onto the current timestamp.
- Finally, we printed out the new date and time using PHP’s date function.
When I ran the code above, I received the following result:
2 hour(s) added onto 03/01/20 14:10 becomes 03/01/20 16:10
Adding hours onto a date and time using PHP’s DateTime object.
If you want to use the DateTime object for this operation, then you can use the following example:
//Get the current date and time. $current = new DateTime(); //The number of hours to add. $hoursToAdd = 2; //Add the hours by using the DateTime::add method in //conjunction with the DateInterval object. $current->add(new DateInterval("PTH")); //Format the new time into a more human-friendly format //and print it out. $newTime = $current->format('Y-m-d H:i'); echo $newTime;
As you can see, you do not need to do any multiplication sums while using the DateTime object, as it comes equipped with a handy method called DateTime::add.
In the code above, we simply passed a DateInterval object into this method. Our DateInterval object had PT2H set as the $interval_spec parameter, which basically translates into “a period of two hours.”
Other examples of what you could pass into the constructor of the DateInterval object:
- PT1H: A period of one hour.
- PT6H: A period of six hours.
- PT24H: A period of 24 hours.
The most important thing in this case is that we use the letter “H” as the Period Designator.
Related tutorials:
date_add
Прибавляет заданный объект DateInterval к объекту DateTime.
Список параметров
Только для процедурного стиля: Объект DateTime, возвращаемый date_create(). Функция изменяет этот объект.
Возвращаемые значения
Возвращает объект DateTime для применения в цепи методов или FALSE в случае возникновения ошибки.
Примеры
Пример #1 Пример использования DateTime::add()
$date = new DateTime('2000-01-01'); $date->add(new DateInterval('P10D')); echo $date->format('Y-m-d') . "\n";
$date = date_create('2000-01-01'); date_add($date, date_interval_create_from_date_string('10 days')); echo date_format($date, 'Y-m-d');
Результат выполнения данных примеров:
Пример #2 Другие примеры с DateTime::add()
$date = new DateTime('2000-01-01'); $date->add(new DateInterval('PT10H30S')); echo $date->format('Y-m-d H:i:s') . "\n"; $date = new DateTime('2000-01-01'); $date->add(new DateInterval('P7Y5M4DT4H3M2S')); echo $date->format('Y-m-d H:i:s') . "\n";
Результат выполнения данного примера:
2000-01-01 10:00:30 2007-06-05 04:03:02
Пример #3 Будьте внимательны при добавлении месяцев
$date = new DateTime('2000-12-31'); $interval = new DateInterval('P1M'); $date->add($interval); echo $date->format('Y-m-d') . "\n"; $date->add($interval); echo $date->format('Y-m-d') . "\n";
Результат выполнения данного примера:
Примечания
При работе с PHP 5.2 в качестве альтернативы можно воспользоваться функцией DateTime::modify().
Смотрите также
- DateTime::sub() — Вычитает заданное количество дней, месяцев, лет, часов, минут и секунд из времени объекта DateTime
- DateTime::diff() — Возвращает разницу между двумя DateTime объектами
- DateTime::modify() — Изменение временной метки
Описание класса datetime, примеры использования класса datetime.