Change today's date and time in php

后端 未结 5 934
孤城傲影
孤城傲影 2020-12-17 09:11

Is it possible to change php\'s current date and time (something like set_time(strtotime(\'1999-09-09\')) so when i call time() it will return me timestamp for 1999-09-09? I

5条回答
  •  旧巷少年郎
    2020-12-17 10:05

    No it isn't. PHP gets its time from the system time. The only way you can change what PHP sees as the time is to change the system time.

    It may be feasible for you to do that using exec() or something similar, but probably not advisable.

    A better solution may be to create your own time function, which you can specify, using an offset.

    eg:

    function mytime() {
        return time()+set_mytime();
    }
    
    function set_mytime($new_time=null) {
        static $offset;
        if(!$new_time) {return $offset;}
        //$new_time should be a unix timestamp as generated by time(), mktime() or strtotime(), etc
        $real_time=time();
        $offset=$real_time-$new_time;
    }
    
    //usage:
    set_mytime(strtotime("1999-09-09");
    $faketime=mytime();
    .... do something that takes a bit of time ....
    $faketime2=mytime();
    

    That's just something I've thrown together quickly for you. I haven't tested it, so there may be (probably are) bugs, but I hope it gives you enough to get a solution.

提交回复
热议问题