PHP date_time_set() Function
The PHP date_time_set() function sets the time of a DateTime object. This function is an alias of DateTime::setTime() method.
Syntax
//Object-oriented style public DateTime::setTime(hour, minute, second, microsecond) //Procedural style date_time_set(object, hour, minute, second, microsecond)
Parameters
object |
Required. For procedural style only: A DateTime object returned by date_create(). |
hour |
Required. Specify an integer value representing hour of the time. |
minute |
Required. Specify an integer value representing minute of the time. |
second |
Optional. Specify an integer value representing second of the time. Default is 0. |
microsecond |
Optional. Specify an integer value representing microsecond of the time. Default is 0. |
Return Value
Returns the DateTime object with modified time on success, otherwise returns false.
Example: using both styles
The example below shows the usage of date_time_set() function.
<?php //creating a DateTime object $date = date_create(); //setting time using Object-oriented style $date->setTime(5, 10); //formatting the datetime to print it echo date_format($date, "d-M-Y H:i:s")."\n"; //setting time using Procedural style date_time_set($date, 10, 48); //formatting the datetime to print it echo date_format($date, "d-M-Y H:i:s")."\n"; ?>
The output of the above code will be:
11-Sep-2021 05:10:00 11-Sep-2021 10:48:00
Example: Modifying time of a DateTime object
This function can be used to modify time of the DateTime object to a new value. Consider the example below:
<?php //datetime string $datetime_string = "14-May-2015 5:10"; //creating a DateTime object $date = date_create($datetime_string); //formatting the datetime to print it echo "Original DateTime: ".date_format($date, "d-M-Y H:i:s")."\n"; //setting time to a new value date_time_set($date, 11, 15); //formatting the datetime to print it echo "Modified DateTime: ".date_format($date, "d-M-Y H:i:s")."\n"; ?>
The output of the above code will be:
Original DateTime: 14-May-2015 05:10:00 Modified DateTime: 14-May-2015 11:15:00
Example: Adding values exceeding ranges
When values exceeding ranges are passed to this function, they will be added to their parent values. Consider the example below:
<?php //creating a DateTime object $date = date_create("20-May-2015"); //setting time to a new value date_time_set($date, 5, 10); echo date_format($date, "d-M-Y H:i:s") . "\n"; //setting time with exceeding range of minutes - //exceeding minutes (5 minutes) will be added date_time_set($date, 5, 65); echo date_format($date, "d-M-Y H:i:s") . "\n"; //setting time with exceeding range of hours - //exceeding hours (2 hours) will be added date_time_set($date, 26, 10); echo date_format($date, "d-M-Y H:i:s") . "\n"; ?>
The output of the above code will be:
20-May-2015 05:10:00 20-May-2015 06:05:00 21-May-2015 02:10:00
❮ PHP Date and Time Reference