Yii date, hour, minute -> datetime string -> MySQL datetime - php

I'm using Yii to construct a web application. One of my input forms has a CJuiDatePicker for the date. I have two drop down lists, one for the hours, and one for the minutes.
My problem is in the data model, where I'm trying to convert the date, hour, and minute from the form into a MySQL datetime string. I have to produce a datetime string that looks like this - 2011-02-27 20:11:56, so Yii can convert the string into a MySQL datetime and insert the value into the row.
In the model, I have a rule that looks like this:
array('event_datetime_from', 'createDatetime',
'date'=>'event_date_from', 'hour'=>'event_hour_from',
'minute'=>'event_minute_from'),
The createDateTime validator function looks like this:
public function createDatetime($attribute, $params) {
if (!$this->hasErrors()) {
$date = $this->$params['date'];
$hour = $this->$params['hour'];
$minute = $this->$params['minute'];
if (trim($date) === '') {
$this->$attribute = null;
} else {
$parse = CDateTimeParser::parse(
$date.' '.$hour.':'.$minute,
'MM/dd/yyyy hh:mm');
$this->$attribute = date('Y-m-d H:i:s', $parse);
}
}
}
Now, I'm not a PHP developer. However, it appears to me that $params['date'] is returning the string value event_date_from, rather than the value of event_date_from.
My PHP question is, how do I get the value of event_date_from inside the createDateTime validator function?
My apologies if I overlooked the answer somewhere in the Yii documentation. I couldn't find many examples of validator functions. The Yii validator classes have a different parameter signature than validator functions.
Edited based on thaddeusmt's answer:
I tried extending CActiveRecord and coded an afterValidate method, but I couldn't find a place to define my working date, hour, and minute variables. I defined them in the extended method, and the afterValidate method couldn't see them. I got a PHP undefined variable error in the afterValidate method.
In the controller, I coded the following function:
protected function createDateTime($dateString, $hour, $minute) {
if (trim($dateString) == '') {
return null;
} else {
$timeString = $dateString.' '.$hour.':'.$minute;
return date('Y-m-d H:i:s', strtotime($timeString));
}
}
It should be a cinch to call a function in PHP, right?
I tried both of these calls in the actionCreate() function:
$model->event_datetime_from =
createDateTime($_POST['event_date_from'],
$_POST['event_hour_from'],
$_POST['event_minute_from']
);
and:
$model->event_datetime_from =
createDateTime($model->event_date_from,
$model->event_hour_from,
$model->event_minute_from
);
My controller code dies with either of these calls, and I get a blank (no HTML) response page.
I thought what I wanted to do was pretty simple. I want to take a date, hour, and minute string, and convert the concatenation to a datetime string. What am I missing?

What I do is, in the POST action in the Controller (where the POST vars are assigned), I convert the posted date and time values into a MySQL datetime with the date() and mktime() function, then validate/save. So, here is an example of the post action:
public function actionUpdate() {
$model=$this->loadModel();
if(isset($_POST['Model'])) {
$model->attributes = $_POST['Model']; // assign the rest of the POST vars here
$model->event_datetime_from = date(
'Y-m-d H:i:s', // convert the timestamp to the mySQL format
mktime( // create the timestamp from the posted date and time vars
$_POST['my-hour-var'], // set the hour
$_POST['my-minute-var'], // set the min
$_POST['my-second-var'], // set the sec
date("m"), // set the month
date("d"), // set the day
date("Y") // set the year
)
); // create a MySQL Y-m-d H:i:s format date from the POST vars
$model->save(); // this run the validation rules, naturally
}
}
(This assumes a model called "Model", POSTed hour, minute and second variables called my-hour-var, my-minute-var and my-second-var respectively, and that you are setting the DATE part to today.)
And here is an example of validation rule in the Model model using the CTypeValidator:
public function rules() {
return array(
array('event_datetime_from', 'type', 'type'=>'datetime', 'datetimeFormat'=>'yyyy-MM-dd hh:mm:ss', 'message' => '{attribute} is not a date and time!'),
}
I hope this helps!

I'd highly recommend checking out this extension:
http://www.yiiframework.com/extension/i18n-datetime-behavior/
It does some of this behavior automatically. You may need to update it a bit depending on how you expect your incoming dates to look. One way is to always run the property through strtotime() (built in php date parsing function) instead of the specific date parser in the extension.

I finally got my date, hour, and minute strings to convert to a datetime string.
Here's the code that I put in the actionCreate method and the actionUpdate method of the CalendarEventController:
$model->attributes=$_POST['CalendarEvent'];
// new code
$timeString = $_POST['CalendarEvent']['event_date_from'].' '.
$_POST['CalendarEvent']['event_hour_from'].':'.
$_POST['CalendarEvent']['event_minute_from'];
$model->event_datetime_from =
date('Y-m-d H:i:s', strtotime($timeString));
if (trim($_POST['CalendarEvent']['event_date_to']) === '') {
$model->event_datetime_to = null;
} else {
$timeString = $_POST['CalendarEvent']['event_date_to'].' '.
$_POST['CalendarEvent']['event_hour_to'].':'.
$_POST['CalendarEvent']['event_minute_to'];
$model->event_datetime_to =
date('Y-m-d H:i:s', strtotime($timeString));
}
I had two datetime fields in this model, with the second field optional. This code didn't work when I put it in a function. It only worked when I put the code inline in the two action methods.
I guess I don't understand PHP function calls. But, in case anyone else comes across this question, here's the answer that worked.

Related

Laravel Carbon addHours response modification

I have a booking table where there's a bookingtime datetime field and duration field.
The duration field is integer.
In my get query for the calendar, I am showing the duration so I am trying to :
add the duration to the booking time date.
I am using this in the end of my query:
for ($i=0;$i<count($query);$i++){
$durationdate = Carbon::parse($query[$i]->bookingtime)->addHours($query[$i]->duration);
$query[$i]->end = $durationdate;
}
return $query.
The query is returning everything fine. but the "end" is returning an object
end{ date:"..." , timezone_type:3, timezon: "UTC"}
I want to modify the end to be returned like the other data in my query response as :
end : "2018-02-01 12:00:00" for example
Use the toDateTimeString() method like this:
$query[$i]->end = $durationdate->toDateTimeString();
Or the format() method:
$query[$i]->end = $durationdate->format('Y-m-d H:i:s');
The object returns is of type DateTime, so you can use the format() function to get the expect date 2018-02-01 12:00:00
$query[$i]->end = $durationdate->format('Y-m-d H:i:s');

avoid time/date overlapping in mysql (laravel)

I have an iOS app where users can reserve a car either daily or hourly and if a user reserves one car other user can't reserve it till the first reservation is over. I'm using Laravel as the API to save data to MySQL database.
The format of time and date are like this 27 Dec 2016 15:21. I'm saving the data
public function requested(Request $request)
{
$time = new Reservation();
$time->from_date = $request->from_date;
$time->to_date = $request->to_date;
$time->from_time = $request->from_time;
$time->to_time = $request->to_time;
}
but this won't prevent time overlapping for sure so I tried this
$carCount = Reservation::where(
function ($query) use ($startTime, $endTime) {
$query->where('from_time', '<', $endTime)
->where('to_time', '>', $startTime);
}
)->count();
if ($carCount > 0) {
return response()->json(['request' => 'no']); // this response just to check
} else {
$carRoom->save();
response()->json(['request' => 'yes']);
}
then I thought this isn't working because of date/time format. But I wanted to make sure what format I should convert the date in laravel?
this is my migration for Reservation:
$table->string('from_date')->nullable();
$table->string('to_date')->nullable();
$table->string('from_time')->nullable();
$table->string('to_time')->nullable();
I made the string because I wasn't sure if Time or anything is the right one
My main question is how can I avoid time and date overlapping in my app's database?
Store the dates in the database as timestamps
then your query should work as intended then convert the incoming dates:
27 Dec 2016 15:21
to timestamps using strtotime() or with datetime objects
both are part of PHP check the PHP documentation to see more information.

Carbon create date trailing data error

I'm trying to create a carbon date as follows to store in a timestamp column:
'from_dt' => Carbon::createFromFormat('Y-m-d', Carbon::now()->year . '-04-01'),
'to_dt' => Carbon::createFromFormat('Y-m-d', Carbon::now()->addYear() . '-03-31'),
But I'm getting an [InvalidArgumentException] Trailing data exception.
In my model I have set the protect dates property as follows:
// ensure dates are accessed and set as a date
protected $dates = ['from_dt', 'to_dt'];
What the correct way to set a date using carbon and how can I automatically work out the to_dt one year from the from_dt - currently I'm having to hard code the day and month of the to_dt.
Managed to fix it. Solution below.
'from_dt' => Carbon::parse(Carbon::now()->year . '-04-01'),
'to_dt' => Carbon::parse(Carbon::now()->addYear()->year . '-03-31'),
I have also same issue . i was using wrong format.
Now it is fix by following code
$dob = Carbon::createFromFormat('d-m-Y', $input['date_of_birth']);
$input['date_of_birth'] = $dob->format('Y-m-d');

Trouble with date and time formats saving in my database

I have trouble saving my date and time values. I tried different formats, here the actual try.
validator in my form:
$datum=$this->CreateElement('text','datum')
->setAttrib('size', '10')
->addValidator(New Zend_Validate_Date('MM-DD-YYYY'));
$zeit=$this->CreateElement('text','zeit')
->setAttrib('size', '10')
->addValidator(new Zend_Validate_Date(array('format' => 'H:i:s')));
Snippet of my Controller addAction
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$logenr = $this->_getParam('kopfnr', 0);
$kopfnr = $logenr;
$dat= $form->getValue('datum');
$zeit = $form->getValue('zeit');
$thema = $form->getValue('thema');
$aktermine = new Application_Model_DbTable_Aktermine();
$aktermine->addTermine( $kopfnr, $dat, $zeit, $thema);
And, my add function in my database class:
public function addTermine($kopfnr, $datum, $zeit, $thema)
{
$data = array(
'kopfnr' => $kopfnr,
'datum' => $datum,
'zeit' => $zeit,
'thema' => $thema,
);
$this->insert($data);
}
I´m using a mySQL database on a WAMP installation.
Where is my error? As a remark I want to say, I get a new record, the value of "thema" and the keys are properly saved, so I think it must be some format thing somewhere.
EDIT: I get a new record but the fields date and time are empty. I get no errors
NEW: I added a debug test in my controller to see what comes for the date value, here is the answer:
string '01-04-2016' (length=10)
(I put in 01-04-2016)
By reading your comments I understand you have two problems. The first one is putting the date into your table and the second is to let the user use the normal date format (dd/mm/yyyy).
First problem is solved when you reformat the user input before putting it into the database.You can add the following line into the $form->isValid($formData) part:
$dat = (new DateTime($form->getValue('datum')))->format('Y-m-d');
This oneliner will convert the date from 'dd-mm-yyyy' to 'yyyy-mm-dd'.
thanks, after the suggestion to debug I changed the format of my date like this: $test1=date('Y/m/d',strtotime($dat));
And now it works!

How to set current date and time in table field using zend

I am having table called users with following fields ,
is_login(tinyint(1)) and last_login(datetime).
Below is the piece of code to update when user is online using Zend,
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1,'last_login'=>$currentDateTime);
$this->_db->update( 'users', $data,'id = '.$id);
}
Here i am using $currentDateTime = date('Y-m-d H:i:s'); to store current data and time. But it seems not ok with time.
Kindly suggest me the best way to store current data and time using Zend .
Thanks in Advance,
Dinesh Kumar Manoharan
I'm not exactly sure what's causing your problem, but I find using NOW() to be easier. Also, you should ensure the variable $id gets quoted in the update's where condition.
public function updateLastLoginDetails($id){
$data = array('is_online' => 1, 'last_login' => new Zend_Db_Expr('NOW()'));
$this->_db->update('users', $data, array('id = ?' => $id));
}
It looks like you forgot to use $data anywhere in your code!
public function updateLastLoginDetails($id){
$currentDateTime = date('Y-m-d H:i:s');
$data = array('is_online' => 1, 'last_login'=>$currentDateTime);
$this->_db->update('users', $data, 'id = '. (int)$id);
}
You might want to consider using a TIMESTAMP field in place of a DATETIME for last_login and have MySQL update it automagically.
Hi am I understanding correctly that the year month and day are being inserted correctly but not the hour minutes and seconds? If that is the case can you please provide use with a describe of the users table. Just execute "DESCRIBE users" in phpMyAdmin.
If that is the case it could be that the field is of type DATE and not DATETIME.

Categories