Php convert 2 digit year to 4

Convert 2 Digit Year to 4 Digit Year in PHP

In PHP, you can convert a 2-digit year to a 4-digit year using the date_format() function or the strtotime() function.

Using the date_format() Function:

The date_format() function is used to format a date object in a specific way. You can use it to convert a 2-digit year to a 4-digit year by first creating a date object with the 2-digit year and then formatting it.

        $twoDigitYear = '21'; // Example 2-digit year to convert
        
        $date = date_create_from_format('y', $twoDigitYear); // Create a date object
        $fourDigitYear = date_format($date, 'Y'); // Format the date object to get the 4-digit year
        
        echo $fourDigitYear; // Output: 2021
    

In the above example, we first create a date object using the date_create_from_format() function and passing the format ‘y’ to indicate the 2-digit year. Then we use the date_format() function to format the date object and retrieve the 4-digit year using the format ‘Y’. Finally, we echo the value of the 4-digit year.

Using the strtotime() Function:

The strtotime() function is used to parse a date or time string and return the corresponding Unix timestamp. It can also be used to convert a 2-digit year to a 4-digit year by specifying the input format.

        $twoDigitYear = '21'; // Example 2-digit year to convert
        
        $timestamp = strtotime($twoDigitYear); // Convert the 2-digit year to a Unix timestamp
        $fourDigitYear = date('Y', $timestamp); // Format the timestamp to get the 4-digit year
        
        echo $fourDigitYear; // Output: 2021
    

In the above example, we use the strtotime() function to convert the 2-digit year to a Unix timestamp. Then we use the date() function to format the timestamp and retrieve the 4-digit year using the format ‘Y’. Finally, we echo the value of the 4-digit year.

Summary:

You can convert a 2-digit year to a 4-digit year in PHP using the date_format() function or the strtotime() function. The date_format() function is used to format a date object, while the strtotime() function can parse a date or time string and return the corresponding Unix timestamp. Both methods allow you to specify the desired output format to obtain the 4-digit year.

Leave a comment