Search code examples
phpseconds

Get seconds from a date to end of month PHP


Pulling a date of subscription from an sql database table we want the customer to have until the end of the month one year later to make a payment. The subscription is just some date within a month. The one year later part is easy, figuring out where the end of that month is and adding it, in seconds, to the one year part is giving me problems.

The date is stored as the number of seconds from unix ground zero. How do I find the number of seconds from that value to the end of that month? I've tried converting the date value to an actual date using m-i-Y

End of Month:

$expDate = date('m-i-Y',$row1["renewDate"]);

This works. I get the last day of that month in string form. But if I try:

$endOfMonth = strtotime($expDate);

Doesn't work....

echo'ing $expDate shows the last day of the month in string form.

echo'ing $endOfMonth returns nothing...

Thanks for any thoughts on this.


Solution

  • strtotime doesn't work properly with arbitrary date formats. You have two options:

    1. Use date_create_from_format to parse custom date formats.
    2. Convert your string to Y-m-d format which strtotime understands automatically.

    For example:

    $date = date('Y-m-t', $row1["renewDate"]);
    $timestamp = strtotime($date);
    

    P.S. As mentioned in comments, you should use t instead of i.