当前周如果日期()函数和来自mysqli的日期

时间:2013-03-18 21:22:24

标签: php date mysqli strtotime

我有一张包含以下内容的表格:

StartWeek  | StartName |
2012-07-16 | 1         |

我想做什么。是采取开始周,当前日期,并计算从那时到现在已经过了多少时间。

到目前为止,我有这个:

function getCurrentWeekName() {
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
    if (!$mysqli) {
        die('There was a problem connecting to the database.');
    }
    else {
        date_default_timezone_set('UTC');
        echo "Current date: ".$current_date = date('Y-m-j')."<br>";
        $mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
        $query = $mysqli->prepare("SELECT StartWeek FROM Week");
        $query->execute();
        $query->bind_result($start_date);
        while ($query->fetch()){
            $start_date = $start_date;
        }
        echo "start date: ".$start_date."<br>";
        echo "time passed: ".$time_passed = strtotime($current_date) - strtotime($start_date)."<br>";
        echo "number of days since start: ".$num_of_days = ceil($time_passed/(86400*7))."<br>";
        $week_num = ceil($num_of_days/7);
        $query = $mysqli->prepare("SELECT StartName FROM Week");
        $query->execute();
        $query->bind_result($start_name);
        while ($query->fetch()){
            echo "Start name: ".$start_name = $start_name."<br>";
        }
        $week_num = $start_name + $week_num;
        echo "Week Number: ".$week_num;
    }
    $mysqli->close();
}

问题是,这会返回以下信息:

Current date: 2013-03-18
start date: 2012-07-16
time passed: -1342394787
number of days since start: -2219
Start name: 1
Week Number: -316

很明显我做错了。我认为这必须与我的时间通过计算有关,也许我不应该使用strtotime。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

如果您只是寻找天数差异,可以directly in MySQL

SELECT DATEDIFF(now(), StartDate) AS diff_in_days

其他差异,例如小时,你也可以做

之类的事情
SELECT unix_timestamp(now()) - unix_timestamp(start_date) AS seconds

答案 1 :(得分:0)

你可以用php date-diff =&gt;做到这一点http://php.net/manual/en/function.date-diff.php

检查您是否可以使用:

//replace the values for $startDate and $endDate:
$startDate = strtotime($startDate); 
$endDate = strtotime($endDate); 
$intervalo = date_diff(date_create($startDate), date_create($endDate));
$out = $intervalo->format("Years:%Y,Months:%M,Days:%d,Hours:%H,Minutes:%i,Seconds:%s");
    if(!$out_in_array)
        return $out;
    $a_out = array();

   array_walk(explode(',',$out),
    function($val,$key) use(&$a_out){
        $v=explode(':',$val);
        $a_out[$v[0]] = $v[1];
    });
    print_r($a_out);