How to get year and month from a date - PHP

How to get year and month from a date - PHP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Parsing Date Components in PHP: Extracting Year and Month

Working with dates in PHP often requires more than just storing a string; you need to manipulate time components to build reports, generate invoices, or filter data. A common requirement is extracting the year and month from a date value, specifically converting a raw date string like 2012-01-05 into its constituent parts: the numeric year 2012 and the localized month name January.

The approach you take depends heavily on whether you need to preserve data integrity or if you are performing quick calculations. Using native PHP functions like date() is straightforward but carries significant risks regarding date formatting. For mission-critical applications, relying on immutable objects like Carbon (often used via the Laravel ecosystem) provides a much safer and more robust foundation.

The Legacy Approach: Native PHP Functions

If you are working within a legacy codebase that avoids external dependencies, the standard library offers immediate solutions. You can use date() to extract specific components directly from a date string or a timestamp.

To extract the four-digit year, you pass the date string into date('Y', $timestamp). To get the month name, you use date('F', $timestamp), where 'F' stands for the full English month name. However, this method requires converting your input string to a timestamp first using strtotime() or checkdate().

$dateValue = '2012-01-05';
$timestamp = strtotime($dateValue);

if ($timestamp !== false) {
    $year = date('Y', $timestamp);
    $monthName = date('F', $timestamp);
    
    echo "Year: {$year}, Month: {$monthName}"; 
    // Output: Year: 2012, Month: January
} else {
    echo "Invalid date format.";
}

While this works for simple cases, it has distinct pitfalls. The date() function relies on the server's current timezone and locale settings unless explicitly configured. If your application runs in a server set to UTC but expects US English month names without proper setlocale() calls, you might encounter unexpected results or empty strings for certain locales. Furthermore, parsing invalid dates with strtotime() can lead to silent failures where it defaults to the current time rather than throwing an error, potentially corrupting your data logic downstream.

The Modern Approach: Carbon and DateTimeImmutable

In modern PHP development, particularly within frameworks like Laravel, the preferred solution is to utilize the Carbon library or the built-in DateTimeInterface. These tools abstract away the complexity of timezone handling, locale formatting, and date validation.

Using Carbon, you can instantiate an object from your string and access properties directly. This method is type-safe and handles edge cases like leap years or invalid dates much more gracefully than native functions.

use Carbon\Carbon;

$dateValue = '2012-01-05';
$carbonDate = Carbon::parse($dateValue);

$year = $carbonDate->year;           // Returns 2012 (integer)
$monthName = $carbonDate->isoFormat('MMMM'); // Returns 'January'

// Alternatively, using the native DateTimeImmutable class
$dateObj = new DateTimeImmutable($dateValue);
$nativeYear = (int)$dateObj->format('Y');
$nativeMonthName = (string)$dateObj->format('F');

The Carbon approach allows you to chain methods easily. You can modify the date before extracting components, such as adding a month or filtering by year, without creating a mutable object that might cause side effects elsewhere in your application. The DateTimeImmutable class offers similar benefits with zero external dependencies, making it ideal for tight memory constraints or strict dependency policies.

Handling Locales and Formatting Consistency

One of the most frequent oversights when extracting month names is assuming the output will always be "January" regardless of the server environment. Native PHP functions depend on the system locale. If you are building a global application, relying on date('F') might serve an audience expecting French months if the server locale isn't explicitly set to English.

When using Carbon, you can enforce a specific locale when formatting: $carbonDate->isoFormat('MMMM', ['locale' => 'en_US']);. This ensures consistency across different environments. If you stick with native DateTime objects, remember that format('F') will respect the current process locale, so you must ensure your application sets setlocale(LC_TIME, 'en_US.UTF-8') at the start of the request if consistent English output is required.

For high-volume applications processing dates in bulk, object-oriented approaches using Carbon or DateTimeImmutable are generally preferred over repeated calls to strtotime(). The overhead of creating objects is negligible compared to the complexity and potential errors introduced by string manipulation and timezone guessing. Always validate your input date format before parsing it to prevent invalid timestamps from slipping into your logic flow.

Our network