PHP Function Reference

PHP DateTimeImmutable - setTime() Method



The PHP DateTimeImmutable::setTime() method returns a DateTimeImmutable object with time set to the specified time.

Syntax

public DateTimeImmutable::setTime(hour, minute, 
                             second, microsecond)

Parameters

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 a new DateTimeImmutable object with time set to the specified time on success, otherwise returns false.

Example: Sets the time

The example below shows the usage of DateTimeImmutable::setTime() method.

<?php
  //datetime string
  $datetime_string = "14-May-2015 5:10";

  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable($datetime_string);

  //creating a new DateTimeImmutable object 
  //with time set to new value
  $date_new = $date->setTime(2016, 10, 18); 

  //formatting the datetime to print it
  echo "Original DateTime: ".$date->format("d-M-Y H:i:s")."\n";
  echo "New DateTime:      ".$date_new->format("d-M-Y H:i:s")."\n";
?>

The output of the above code will be:

Original DateTime: 14-May-2015 05:10:00
New DateTime:      06-Aug-2015 00:10:18

Example: Adding values exceeding ranges

When values exceeding ranges are passed to this method, they will be added to their parent values. Consider the example below:

<?php
  //creating a DateTimeImmutable object
  $date = new DateTimeImmutable("20-May-2015");

  //setting time to a new value
  $date_new = $date->setTime(5, 10);
  echo $date_new->format("d-M-Y H:i:s") . "\n";

  //setting time with exceeding range of minutes -
  //exceeding minutes (5 minutes) will be added
  $date_new = $date->setTime(5, 65);
  echo $date_new->format("d-M-Y H:i:s") . "\n";

  //setting time with exceeding range of hours -
  //exceeding hours (2 hours) will be added
  $date_new = $date->setTime(26, 10);
  echo $date_new->format("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