PHP Function Reference

PHP DateTimeImmutable - setISODate() Method



The PHP DateTimeImmutable::setISODate() method returns a DateTimeImmutable object with date set to the specified date, according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.

Syntax

public DateTimeImmutable::setISODate(year, week, dayOfWeek)

Parameters

year Required. Specify an integer value representing year of the date.
week Required. Specify an integer value representing week of the date.
dayOfWeek Optional. Specify an integer value representing the day of the week. Default is 1.

Return Value

Returns a new DateTimeImmutable object with date set to the specified date on success, otherwise returns false.

Example: Sets the date

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

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

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

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

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

The output of the above code will be:

Original date: 14-May-2015
New date:      10-Mar-2016

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();

  //setting date to a new value
  $date_new = $date->setISODate(2001, 10, 2);
  echo $date_new->format('d-M-Y') . "\n";

  //setting date with exceeding range of dayOfWeek -
  //exceeding days (2 days) will be added 
  $date_new = $date->setISODate(2001, 10, 9);
  echo $date_new->format('d-M-Y') . "\n";

  //setting date with exceeding range of week -
  //exceeding weeks (3 weeks) will be added
  $date_new = $date->setISODate(2001, 55, 2);
  echo $date_new->format('d-M-Y') . "\n";
?>

The output of the above code will be:

06-Mar-2001
13-Mar-2001
15-Jan-2002

Example: Finding the month a week is in

The example below illustrates on finding the month a week is in.

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

  //setting date to a new value
  $date_new = $date->setISODate(2001, 10);

  //finding the month the week is in
  echo $date_new->format('n') . "\n";
?>

The output of the above code will be:

3

❮ PHP Date and Time Reference