How To Get Year From Date In Php

Working with dates is a common task when developing web applications. In this blog post, we will learn how to extract the year from a given date using PHP.

Using date() and strtotime() Functions

The date() function is used to format a date or a time in PHP. The strtotime() function is used to convert a date string into a Unix timestamp. You can use these functions together to extract the year from a date. Here’s an example:

In this example, we have a date in the format YYYY-MM-DD. We use date(“Y”, strtotime($date)) to extract the year from the given date. The letter “Y” in the date function represents the year (4 digits). The output will be:

    The year is: 2022
    

Using DateTime Class

Another way to extract the year from a date is by using the DateTime class. The DateTime class is built-in to PHP and provides methods for working with dates and times. Here’s an example:

In this example, we create a new DateTime object with the given date. We then use the $dateTime->format(“Y”) method to extract the year from the date. The output will be the same as the previous example:

    The year is: 2022
    

Conclusion

In this blog post, we learned how to extract the year from a given date using PHP. We learned how to use the date() and strtotime() functions together, as well as how to use the DateTime class. Both methods are efficient and easy to use, so choose the one that you find more convenient for your needs.