user587064
user587064

Reputation: 37

Date problem in PHP

I have a piece of PHP that is trying to do this: 1) given a string like "h m s" (where h=hr, m=min, s=sec) 2) Add the time from 1) to time() 3) format the result to look like "y-mth-d-h-min-s"

So say the time is now 01-01-2011 1am, I want it to add "10 0 0", which should give me 01-01-2011 11am, but for some reason at the moment, it does seem to add the string, but it's not accurate.

This is the code I'm using:

$values_arr['regx_expdate'] = date("Y-m-d H:i:s", time()+$values_arr['regx_expdate']);

where $values_arr['regx_expdate'] is the string in the format "h m s", eg. "10 0 0".

The main question is how would time() know if "10 0 0" is actually 10hrs 0min 0min, and not 10days 0hr 0min??

Upvotes: 1

Views: 260

Answers (5)

Hernantz
Hernantz

Reputation: 566

To handle and convert dates in php you should first force everything into unixtimestamp and then you give it the structure you want

$date = date("THE-DATE-FORMAT-YOU-WANT", "THE-DATE-YOU-WOULD-LIKE-TO-CONVERT-IN-SECONDS");

//For example.

$new_date = date("Y-m-d H:i:s", strtotime($old_date));

$now = date("Y-m-d H:i:s", time());

Upvotes: 0

dbwebtek
dbwebtek

Reputation: 245

This little function may help, you may customize it to suit your purpose:

function AddingDaysFromNow($number_of_days)
    {
        $today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
         // today is now time return in seconds

        $addingTime = $today + (86400 * $number_of_days);
         // adding to advance it

        //choice a date form at here
        return date("Y-m-d", $addingTime);
    }

    //use it as 
      $expireDate = AddingDaysFromNow(2);  // assume the 2 is advance to 2 days ahead
                                           // return the day in future

Good luck!

Upvotes: 0

LrdCasimir
LrdCasimir

Reputation: 123

After parsing your input string into Hours Minutes and Seconds, it might be worth reorganizing said array of values into a string that PHP's strtotime can process.

Upvotes: 0

Phil
Phil

Reputation: 164733

Easiest method I can think of is to extract each token from $values_arr['regx_expdate'], add up the seconds and simple add it to time().

For example

if (preg_match('/^(\d{1,2}) (\d{1,2}) (\d{1,2})$/', $values_arr['regx_expdate'], $units)) {
    $seconds = $units[3] + ($units[2] * 60) + ($units[1] * 3600);

    $newTimestamp = time() + $seconds;
}

Upvotes: 0

AndreKR
AndreKR

Reputation: 33658

It does not.

It will cast it to int, interpret it as seconds and add it to the result of time().

Some code that could do as you describe would be:

list ($h,$m,$s) = explode(' ', $values_arr['regx_expdate'], 3);
$difference = 60*60*$h + 60*$m + $s;
$values_arr['regx_expdate'] = date("Y-m-d H:i:s", time()+$difference);

Upvotes: 1

Related Questions