简体   繁体   中英

default date() should be 3 months ahead

My server has many application instances.

I came across a problem that one of my application instance needs to be tested with the future date. ie I want to test the application as it is running in 2013.

If i change the system date then it will work fine but the other instances will also get effected.

I want the future date for only one instance and the rest should work as it is.

ie if i use date('Ym-d'); it should jump for 3 months and display the future date.

and i dont want to add seconds to the default date as that might be a huge change in my application.

And that's why you write your application in a way that is testable .

Not good:

function doSomething() {
    $date = date('Y-m-d');
    ...
}

Good:

function doSomething($ts = null) {
    if (!$ts) {
        $ts = time();
    }
    $date = date('Y-m-d', $ts);
    ...
}

you can make your own date function. It would serve as a hook to all date usage.

function mydate($format) {
    $jump = ' +3 months';
    return date($format, strtotime(date($format) . $jump));
}

you can than change all occurrences of date to mydate . If you decide to switch back to present, just leave $jump = ''

你可以这样做

date('Y-m-d', time() + 3 * 30 * 24 * 3600);

I recommend using the PHP5 DateTime classes. They're a bit more wordy, but much more powerful than the old-style PHP date handling functions.

$dateNow = new DateTime();
$dateAhead = $dateNow->add(DateInterval::createFromDateString('3 months'));

print $dateAhead->format('Y-m-d');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM