How To Get Month And Year From Date In Php

In this blog post, we will learn how to extract the month and year from a given date using PHP. PHP provides us with various functions to manipulate and format dates. We are going to use the date() and strtotime() functions to achieve this task.

Using the date() function

The date() function is used to format a given date or the current date and time. It takes two arguments: the format string and the optional timestamp. If the timestamp is not provided, the current date and time will be used.

Here’s an example of how to extract the month and year from a date string:


    // The given date string
    $date = "2022-08-15";

    // Extracting the month and year
    $month = date("m", strtotime($date));
    $year = date("Y", strtotime($date));

    // Displaying the month and year
    echo "Month: $month | Year: $year";
    

In this example, we first convert the date string to a timestamp using the strtotime() function. Then, we use the date() function to format the timestamp and extract the month and year. The format string “m” is used for the month, and “Y” is used for the year.

Using DateTime class

Another approach to extract the month and year from a date string is by using the DateTime class. Here’s an example:


    // The given date string
    $date = "2022-08-15";

    // Creating a DateTime object
    $dateTime = new DateTime($date);

    // Extracting the month and year
    $month = $dateTime->format("m");
    $year = $dateTime->format("Y");

    // Displaying the month and year
    echo "Month: $month | Year: $year";
    

In this example, we create a DateTime object from the given date string. Then, we use the format() method to extract the month and year from the DateTime object.

Conclusion

In this blog post, we learned how to extract the month and year from a date string in PHP using the date() function and the DateTime class. Both methods can be used to achieve the same result, depending on your preference and the specific use case.