Carbon create date trailing data error - php

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');

Related

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!

ZF2 validating date and time format PT_BR always The input does not appear to be a valid date

Project utilizing ZF2 + Doctrine 2.
I Tried many formats. I'm working with a Form without validation.
My last try was:
$traindate = new Element\DateTime('trainDate');
$traindate->setAttributes(array(
'name' => 'trainDate',
'id' => 'trainDate',
'size' => '30',
'class' => 'datepicker',
'options' => array(
'label' => '',
'format' => 'd-m-Y H:i'
),
));
I need to use a input to set a date and time of a event. On Brazil the basic format is:
14-05-2014 14:20
15-05-2015 15:00
With means Days Months Year Hour Minutes, like I'm expressing on the Options -> Format.
This way always when I try to insert, i get the following messsage:
The input does not appear to be a valid date
Removing the format, i can only pass by $form->isValid($data) by Y-m-d (American Format), but by the way i can't pass time to date too, which is causing me big troubles.
I need to set date PT_BR on Form/Input, Pass by validation, Convert Data do Mysql Format (YYYY-mm-dd HH:ii:ss).
And then retrive from db and convert back to pt_br format.
But not even i can pass time with date to zf2 form, ever this error message.
I remove all filters from this form trying to get work, but doesn't work.
Where is the main problem?
After a long time paying my attention to this problem I found the right and quick solution.
After 6 month making science, I got:
Right all:
$traindate = new Element\DateTime('trainDate');
$traindate->setAttributes(array(
'name' => 'trainDate',
'id' => 'trainDate',
'size' => '30',
'class' => 'datepicker',
));
$traindate->setFormat('d/m/Y'); //ONLY WORKS ON THIS FORMAT.
Docs and people over internet don't make it clear, but to set Format only works on this form.
And to grab this to Entity, you need to write your own Hydrator extending the DoctrineHydrator:
namespace Application\Hydrator;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject;
class MyCustomHydrator extends DoctrineObject {
protected function handleTypeConversions($value, $typeOfField)
{
if($typeOfField == 'datetime'){
return \DateTime::createFromFormat('d/m/Y', $value);
}
return parent::handleTypeConversions($value, $typeOfField);
}
}
It's make it simple to work with any date format. You can extend further making Locale assertions on this Custom Hydrator as you want.
I recommend you to do the date conversion work in your Train entity. The trainData's property getter and setter could be:
//THE PROPERTY IS IN MYSQL FORMAT, BUT THE GETTER WILL RETURN IT ALWAYS IN THE BRAZILIAN ONE
public function getTrainDateTime() {
return $this->trainDateTime->format( 'd/m/Y H:i' );
}
//IT WILL ALWAYS RECIEVE A BRAZILIAN DATETIME, CONVERT IT TO MYSQL FORMAT
public function setTrainDateTime( $trainDateTime ) {
$time = \DateTime::createFromFormat( 'd/m/Y H:i', $trainDateTime )->getTimestamp();
$this->trainDateTime = new \DateTime( date( 'Y-m-d', $time ) );
return $this;
}
If you do it this way, you can always work freely with brazilian dates, without worring about formats. The dirty work will be done by the entity class.

How to structure database and populate Calendar in CodeIgniter 2 project?

I've searched SO and Google and can't quite find what I need.
I'm building a simple Event Calendar with CodeIgniter 2. As per the CodeIgniter documentation, this is the basic code structure and it's working...
// $data[2] contains the data for day #2, etc.
$data[2] = 'event title 1';
$data[8] = 'event title 2<br/>event title 3';
$data[13] = 'event title';
$data[24] = 'event title';
// {content} in template is where $data is inserted for each day
$prefs = array (
// my calendar options
'template' => '
{cal_cell_content}{day}<br/>{content}{/cal_cell_content}
{cal_cell_content_today}<div class="highlight">{day}<br/>{content}</div>{/cal_cell_content_today}'
);
$this->load->library('calendar', $prefs);
$year = ($year === FALSE ? date('Y') : $year);
$month = ($month === FALSE ? date('m') : $month);
echo $this->calendar->generate($year, $month, $data);
Now comes how I've set up my database table...
Each Event has a title field and that creates the $slug. (~/events/view/title-slug)
Each Event has a date field and the data format is mm/dd/yyyy
Now, I'm thinking about how I'd query the database for a particular month/year and extract the data to insert into each $data[] variable.
It seems like I'll need to do the following:
create new columns in my database table for month, day, and year.
take my date input data, after it's validated, and save it into date column.
split apart my date input data, and save each piece into month, day, and year columns.
Then I would simply query my database for year & month, then loop through these results to construct my $data[] array for each day.
Is this the correct way I should be approaching this problem? It seems very redundant to have a date column as well as month, day, and year columns. Can it be done with only the date (mm/dd/yyyy) column? Too simple? Too complex? I'd like to avoid giving the user more than one field for entering a date, and ultimately I'll have a jQuery date-picker to help ensure the proper data format.
I know this may seem like a simple problem, but I've failed to locate simple code examples online. Most of the ones I've found are out of date (CI instead of CI2), too complex for what I'm doing, or use daily content items which have URI segments that already contain the date (~/events/view/yyyy/mm/dd).
EDIT:
This is how my Model is presently setup:
return $this->db->get_where('events', array('yyyy' => $year, 'mm' => $month))->result_array();
You can leave everything as-is and just structure your query to return the month and year as separate columns:
in SQL:
SELECT id,
title,
description,
MONTH(date_field) as event_month,
YEAR(date_field) as event_year
FROM my_table
... etc ...
and in Active Record (taken from here):
$this->db->select('id');
$this->db->select('title');
$this->db->select('description');
$this->db->select("MONTH(date_field) AS event_month");
$this->db->select("YEAR(date_field) AS event_year");
$query = $this->db->get('my_table');
$results = $query->result();
Firstly, I changed my date column into the MySQL "date" format, yyyy-mm-dd, in order to take advantage of the built-in MySQL date functions.
My original $query is as follows, where the 'yyyy' and 'mm' are my redundant "year" and "month" columns:
$this->db->get_where('events', array('yyyy' => $year, 'mm' => $month))->result_array();
I simply changed it into the following using the built-in MySQL date functions:
$this->db->get_where('events', array('YEAR(date)' => $year, 'MONTH(date)' => $month))->result_array();
This solved the question. Now I no longer need to maintain the extra columns for "year" and "month".
Additionally, I can assign the "day" portion of the date column to a virtual column called dd by using the MySQL "alias" function:
$this->db->select('DAY(date) AS dd');
However, this would fail since it over-rides CI's default select('*'). So you'll have to select() all the relevant columns first or it will give an error:
$this->db->select('*');
$this->db->select('DAY(date) AS dd');
And putting it all together in the Model:
// select all relevant columns
$this->db->select('*');
/* use MySQL date functions to creates virtual column called 'dd' containing
"day" portion of the real 'date' column. */
$this->db->select('DAY(date) AS dd');
/* use MySQL date functions to match $year and $month to "year" and "month"
portions of real 'date' column. */
return $this->db->get_where('events', array('YEAR(date)' => $year, 'MONTH(date)' => $month))->result_array();

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

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.

How do I query in cakephp, if the date in the field 'created' of model 'listings' is more than 2 weeks ago?

I have a model 'listing' with a field 'created' which is in a datetime format.
I need to list in a view all listings that were created over 2 weeks ago.
An extra thing if possible is to somehow mark them as expired.
This is in cakePhp 1.27
Hi I think you can use a simple script to do that in cake.
function meScript(){
// first load your model if necessary
$listingModel = ClassRegistry::init('Listing');
// Then set your date margin to , two weeks back
$date_margin = date("Y-m-d H:i:s", strtotime('-2 week')) ;
// now retrieve all records that were created over 2 weeks ago
$listings = $listingModel ->find('all', array(
'conditions' => array('created <' => $date_margin),
)
);
}
That's pretty much it. Since the margin date is in "Y-m-d H:i:s" format, the " 'created <' => $date_margin" condition will retrieve all records that were created before that date.
As for the next step of marking them as expired:
Simply loop through the results and use their ids to set your 'expired' field (or whatever it is called in your database table) to 'true'.

Categories