PHP date to timestamp

Question

Answers ( 1 )

    0
    2024-01-11T18:05:19+00:00

    In PHP, converting a date to a timestamp is a common task, and this can be accomplished using the strtotime() function.

    The strtotime() function is used to convert an English textual datetime description into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC). Here's how you can use it:

    $date = "2024-01-12"; // Example date
    $timestamp = strtotime($date);
    
    echo $timestamp; // Outputs the Unix timestamp
    

    In this example, $date is a string representing the date in a format that strtotime() can understand (like "YYYY-MM-DD"). The function then converts this date into a Unix timestamp, which is stored in the variable $timestamp.

    This method is widely used due to its simplicity and effectiveness in handling a variety of date formats. However, it's important to ensure that the date format is compatible with what strtotime() can parse. If the format is not compatible, the function will return false.

    Another approach, especially useful if you are dealing with different date formats or want more control over the parsing process, is to use the DateTime class:

    $date = "2024-01-12"; // Example date
    $dateTime = new DateTime($date);
    $timestamp = $dateTime->getTimestamp();
    
    echo $timestamp; // Outputs the Unix timestamp
    

    In this case, the DateTime class is used to create a date object from the given string, and then the getTimestamp() method is called on that object to get the Unix timestamp.

    Both methods are valid and widely used in PHP for converting dates to timestamps.

Leave an answer