Skip to content

Setters

The following setters are implemented via PHP's __set() method. Its good to take note here that none of the setters, with the obvious exception of explicitly setting the timezone, will change the timezone of the instance. Specifically, setting the timestamp will not set the corresponding timezone to UTC.

php
$dt = Carbon::now();

$dt->year = 1975;
$dt->month = 13;             // would force year++ and month = 1
$dt->month = 5;
$dt->day = 21;
$dt->hour = 22;
$dt->minute = 32;
$dt->second = 5;

$dt->timestamp = 169957925;  // This will not change the timezone
// Same as:
$dt->setTimestamp(169957925);
$dt->timestamp(169957925);

// Set the timezone via DateTimeZone instance or string
$dt->tz = new \DateTimeZone('Europe/London');
$dt->tz = 'Europe/London';

// The ->timezone is also available for backward compatibility but
// it will be overridden by native php DateTime class as soon as
// the object is dump (passed foreach, serialize, var_export, clone, etc.)
// making the Carbon setter inefficient, if it happen, you can cleanup
// those overridden properties by calling ->cleanupDumpProperties() on
// the instance, but we rather recommend to simply use ->tz instead
// of ->timezone everywhere.

// verbose way:
$dt->setYear(2001);

echo $dt->year;                              // 2001
echo "\n";                                  


// set/get method:
$dt->year(2002);

echo $dt->year();                            // 0000-05-22 03:32:05
echo "\n";                                  


// dynamic way:
$dt->set('year', 2003);

echo $dt->get('year');                       // 2003
echo "\n";                                  

// these methods exist for every unit even for calculated properties such as:
echo $dt->dayOfYear(35)->format('Y-m-d');    // 2003-02-04

Be careful that setters will overflow:

php
echo Carbon::parse('2026-06-14')->setHours(25);        // 2026-06-15 01:00:00
echo "\n";                                            

// This can be especially annoying with days overflowing month:
echo Carbon::parse('2026-06-14')->setDay(31);          // 2026-07-01 00:00:00
echo "\n";                                            
// So setAnchorDay is available to work around this issue,
// it will set current day to the given number if it exists in the current month,
// else it will set it to the last day of the month
echo Carbon::parse('2026-06-14')->setAnchorDay(31);    // 2026-06-30 00:00:00