PHP Function Reference

PHP DateTime - setTime() Method



The PHP DateTime::setTime() method sets the time of a DateTime object. The date_time_set() function is an alias of this 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 DateTime::setTime() method.

<?php
  //creating a DateTime object
  $date = new DateTime();

  //setting time using Object-oriented style
  $date->setTime(5, 10); 

  //formatting the datetime to print it
  echo $date->format("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("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 method 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 = new DateTime($datetime_string);

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

  //setting time to a new value
  $date->setTime(11, 15); 

  //formatting the datetime to print it
  echo "Modified DateTime: ".$date->format("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 method, they will be added to their parent values. Consider the example below:

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

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

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

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