Search code examples
phptimeunix-timestamp

Calculate time() - minutes or hours or weeks or months or years PHP


I currently have a piece of code that fetch a string.

Exemple: 23 minutes ago

My code, if minutes, get the number (23 in this case).

I want to remove minutes (in this case) from the time() unix timestamp value.

I tried :

 $timestamplastcheck = strtotime("-".$minutes." minutes", strtotime(time()));

But it's returning wrong date.

Can someone told me what's wrong? and also, if hours, weeks, months, and years are added the same way?

Much appreciate.


Solution

  • Can use Date with date method modify, example:

    $ago = '23 minutes ago';
    $date = (new \DateTime())->modify($ago);
    $timestamplastcheck = $date->getTimestamp()
    
    echo $date->format('c');
    

    With this you can't need parse your string to get the number, the modify is very powerful. http://php.net/manual/en/datetime.modify.php