The setTime Method of the DateTime Class

The setTime method sets the time in a DateTime object. The first parameter is hours (from 0 to 23), the second is minutes (from 0 to 59), the third is seconds (from 0 to 59), and the fourth is microseconds (optional parameter). It returns the modified DateTime object.

Syntax

phppublic DateTime::setTime(
  int $hour,
  int $minute,
  int $second = 0,
  int $microsecond = 0
): DateTime

Example

Let's set the time to 15:30:00 in a DateTime object:

php<?php
  $date = new DateTime();
  $date->setTime(15, 30);
  echo $date->format('H:i:s');
?>

Code execution result:

php'15:30:00'

Example

Let's set the time with seconds and microseconds:

php<?php
  $date = new DateTime();
  $date->setTime(10, 15, 30, 500000);
  echo $date->format('H:i:s.u');
?>

Code execution result:

php'10:15:30.500000'

Example

Let's set the time and output the full date:

php<?php
  $date = new DateTime('2023-01-01');
  $date->setTime(23, 45);
  echo $date->format('Y-m-d H:i:s');
?>

Code execution result:

php'2023-01-01 23:45:00'

See Also

  • the format method,
    which formats the date according to a given pattern