1

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

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。有人可以帮忙吗?

4

2 回答 2

3

If you're looking for just a difference in days, you can do it directly in MySQL:

SELECT DATEDIFF(now(), StartDate) AS diff_in_days

for other differences, e.g. hours, you can also do things like

SELECT unix_timestamp(now()) - unix_timestamp(start_date) AS seconds
于 2013-03-18T21:27:19.990 回答
0

你可以用 php date-diff => 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);
于 2013-03-18T21:48:25.003 回答