1

I have a table containing the following:

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

What I want to do. Is take the starting week, the current date, and calculate how much time has passed between then and now.

So far I have this:

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();
}

The problem is, this returns the following information:

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

So clearly I'm doing it wrong. I think it must be something to do with my time passed calculation, maybe I shouldn't be using strtotime. Can anybody help?

4

2 に答える 2

3

日数の違いだけを探している場合は、MySQLで直接行うことができます:

SELECT DATEDIFF(now(), StartDate) AS diff_in_days

他の違い、たとえば時間については、次のようなこともできます

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 に答える