Calculating the difference between two times using

2019-09-09 22:17发布

问题:

Hi I have a problem where I am trying to get a total time that a job has taken (using database fields job_start and job_end time(7)) then adding this to another model's field,

the code i have is

 if (isset($_POST['Jobs'])) {

        $model->attributes = $_POST['Jobs'];
        $model->setScenario('closejob');
        $model->status = 2; //set status to closed

        //date time difference - this is the part I need help with 
        $diff = $model->job_start - $model->job_end;
        //need to get customer model and add time diff to it 
        $customermodel = Customers::model()->findByPk($model->customer_ID);
        $customermodel->total_time = $customermodel->total_time + $diff;
        $customermodel->save();



        if ($model->save())
            $this->redirect(array('view', 'id' => $model->job_ID));
    }

I have tried string to time and other date functions but to no avail , the above code throws the following error

CDbCommand failed to execute the SQL statement: SQLSTATE[22007]: [Microsoft][SQL Server Native Client 11.0][SQL Server]Conversion failed when converting date and/or time from character string..

Any ideas on the proper way to do this ? i.e am I going about the adding of time and calculating the differences all wrong ?

I think it has something to do with converting the string to a time format but I am unsure how to do this

回答1:

Maybe you have to do

$diff = $model->job_end - $model->job_start;

Instead of

$diff = $model->job_start - $model->job_end;


回答2:

Unless you have an attached behavior for that model, it is likely that your job_start and job_end attributes are strings that are formatted according to MSSQL, assuming the column types are a date/time representation. This is certainly the way CActiveRecord models work with MySQL and Yii with DATETIME type.

To do differences, you would need to convert first. Take a look at CDateFormatter and use it to convert your attributes to numerical representations that allow for arithmetic.

If you cannot get Xdebug to work, then invest time in getting the Yii::log() function working (it will output to runtime/application.log by default.