Syntax for date_time_set() Function
The syntax of the date_time_set() function in PHP is given below.
The parameters of the function are:
- $object: The DateTime object to modify.
- $hour: The new value for the hour component.
- $minute: The new value for the minute component.
- $second: (Optional) The new value for the second component. The default is 0.
- $microsecond: (Optional) The new value for the microsecond component. The default is 0.
These values must be in the format of a string, with the time formatted in the 24-hour format.
A new DateTime object with the updated time components is returned by the date_time_set() method. The primary DateTime object is unaltered.
Note: It is worth noting that the date_time_set() function does not modify the original DateTime object, instead, it returns a new DateTime object with the specified date and time. This means that if you want to update a DateTime object with a new time value, you need to assign the return value of the date_time_set() function back to the original DateTime object.
In this example, the first line creates a new DateTime object with the date set to December 1st, 2023 at midnight. The second line uses the date_time_set() function to set the time of the object to 12:30 pm and assigns the resulting DateTime object back to the $date variable.
If you pass day and month values that are outside the allowed range while calling this method, they will be added to their parent values.
A new DateTime object that reflects the current date and time is created by the above code. The DateTime object’s time is then set to 24 hours, 22 minutes, and 36 seconds using the date_time_set() method. The date_format() method is then used to format and print the changed date and time.
The date_time_set() function in PHP provides a convenient way to set or modify the time components of a DateTime object. By using this function, developers can easily change the hour, minute, second, and microsecond components of a DateTime object. The date_time_set() function offers flexibility and precision in handling time modifications, making it a valuable tool for working with dates and times in PHP applications.