Jump to content

Archived

This topic is now archived and is closed to further replies.

deltajam_v

PHP Date

Recommended Posts

Hi, I'm pulling a datetime field called 'expires' from the database. I also have a field in the db called 'months' that I would like to add to the expires field.

So if:

$expires = 2006-04-17 09:54:23;
$months = 6;

I want to add the months to the expires variable. How would I do that?

Share this post


Link to post
Share on other sites
I hope I understand you correctly. If so, this will do what you want.

[code]
<?php

    // Your original data
    $expires = "2006-04-17 09:54:23";
    $months = "6";

    // Break the $expires variable into component parts
    $year = substr($expires, 0, 4);
    $month = substr($expires, 5, 2);
    $day = substr($expires, 8, 2);
    $hour = substr($expires, 11, 2);
    $minute = substr($expires, 14, 2);
    $second = substr($expires, 17, 2);

    // Add $months onto $month
    $new_month = $months+$month;

    // If $new_month is only 1 digit, add a preceeding zero
    $strlen = strlen($new_month);
    if($strlen==1) {$new_month = "0$new_month";}

    // Set the $expires variables with the new value
    $expires = "$year-$new_month-$day $hour:$minute:$second";

    // Just so you can see that it works... echo the result.
    echo "$expires";
?>
[/code]

Share this post


Link to post
Share on other sites
Just use the [a href=\"http://www.php.net/strtotime\" target=\"_blank\"]strtotime()[/a] function to add the months:
[code]<?php
    // Your original data
    $expires = "2006-04-17 09:54:23";
    $months = "6";
    $expiration_date = date('Y-m-d H:i:s',strtotime($expires . ' + ' . $months . ' + months'));
    echo $expires . ' + ' . $months . ' months = ' . $expiration_date;
?>
[/code]

Ken

Share this post


Link to post
Share on other sites
Don't worry... ken knows more clever stuff than i do

Share this post


Link to post
Share on other sites
When I use kenrbnsn's code, the output is pretty wacky:

2006-04-17 09:54:23 + 6 months = 1969-12-31 19:00:00


any suggestions?

Share this post


Link to post
Share on other sites
That will happen when the strtotime() functon does not recognize the input as a valid date/time string.  I just tested the code again and it works fine. Please post the code you used to get the invalid result. Also what changed since April when you said it worked fine.

Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.