Getting The Month (Int) From Date

When I create a user I’m saving the date on which he was created with this code in beforeValidate function:


$this->create_time=new CDbExpression('NOW()');

Now , in addition , I need to determine on what season he was created , which means I need to get the month from the create_time field , which is date , as integer.

I tried several php codes but none worked , and now found that yii has some formatMonth() method , but couldn’t find a clear example how to do this.

Heres what I’v wrote so far (which didn’t worked)


$month= formatMonth('M',$this->create_time);

		if($month>=1 AND $month<=9) 

		{

			$this->create_ses='Summer';

		}

		else

		{

			$this->create_ses='Winter';

		}

Any ideas what I wrote wrong?


$month = date('m', $this->create_ses);

doesn’t work?

I guess you meant create_time , and nope it shows the following error:


$month = date('m', strtotime($this->create_ses));

Try this.

because $this->create_ses is a formatted datetime, php date function expect parameter 2 to be a timestamp that’s why you need strtotime function to convert it to timestamp.

The first thing to understand is that this line:




$this->create_time=new CDbExpression('NOW()');



doesn’t execute any SQL query to evaluate the expression. CDbExpression is just a wrapper object around ‘NOW()’ string that indicates that it’s an SQL expression instead of an explicitly defined value. The actual value of create_time is unknown until the record gets saved. The eaiest solution is probably to create timestamp at PHP level:




$this->create_time=date('Y-m-d H:i:s');



Also, storing both create_time and create_ses in the database seems to be redundant and likely to cause maintenance issues. Create_ses can be calculated runtime when required.

Worked. Thanks!

Yes , ageed.

The thing is that I need to be able to filer this value.