How to create DateTime object from string in symfony2/php - php

In a DB table I have several fields with datetime as field type. So I need to persist data only as date time object.
From a form I get date time as string like
2012-10-05 17:45:54
Now when ever I persist my entity I get following error:
Fatal error: Call to a member function format() on a non-object in
..\DateTimeType.php on line 44
I tried with
$protocol->setStartedAt(strtotime($post['started_at']));
or
$from = \DateTime::createFromFormat('yy-mm-dd hh:mm:ss', $post['started_at']);
$protocol->setStartedAt($from);
or just
$from = new \DateTime($post['started_at']);
$protocol->setStartedAt($from);
The last code works but it does not uses the timestamp passed as arguement but just gets the current time.
Any ideas?

I always create a DateTime object with its constructor, in your case it would be:
$protocol->setStartedAt(new \DateTime($post['started_at']));
if this works but does not use the timestamp posted you probably do not have the value in $post['started_at']. Try debugging it or just do the dirty trick:
die($post['started_at']);

For the sake of future readers who surely will someday encounter this problem (this is the first post if you google "symfony 2 datetime from string"), keep in mind that in Symfony 2 the DateTime object does NOT accept a string with that format : "d/m/Y H:i:s", and probably doesn't support many others either.
For the sake of not becoming mad at that, I've actually found out that the easiest and safest solution to avoid such errors is this one:
First, get your date string from whatever kind of request you are doing (In my case a generic AJAX request) and convert it to a DateTime Object, this example assumes that we need to create a dateTime object for 25/04/2015 15:00, which is the format of the jQuery UI italian DateTimePicker (that's just an example):
$literalTime = \DateTime::createFromFormat("d/m/Y H:i","25/04/2015 15:00");
(note: use \ to use php's DateTime object, else you will be using Symfony's datetime object that will throw you an exception)
Then, once you did it, create a date string using the comfort format function, by giving to the first parameter the output format expected (Y-m-d H:i:s):
$expire_date = $literalTime->format("Y-m-d H:i:s");
In this way you are 100% sure that whatever kind of format you are passing or receiving this will properly be converted and you won't get any kind of exception from the DateTime symfony object, as long as you provide what you are expecting as an input.
Knowing that this post is actually quite old, I've just decided to post that because I didn't find any other valuable source but this one to understand where the problem could have been.
Please note that the best solution is still to send the datetime string in the correct format already, but if you literally have no ways to do that the safest way to convert such a string is the one above.

How about createFromFormat?
http://uk.php.net/manual/en/datetime.createfromformat.php
$from = DateTime::createFromFormat($post['started_at'], 'Y-m-d H:i:s');

Related

Php time and datatime object

So,
I know a lot of requests and question has been askeb about this subject but none really worked for my case... I'm working on a liscensing api with php (supposed to be easy) and I get a string date (2000-01-01) from my db and the length of the subscription. So I'm creating a DateTime Object with it using this :
$created_at = date_create($result["created_at"]);
date_add($created_at, date_interval_create_from_date_string($result["length"]." days"));
But for some unknowed reason, It seems I can't get the current date in a DateTime object so I can just compare them with <>=. Even if I use date_sub() or date_diff() It still require two DateTime object. I'm really deseperate at this point so I figured I could ask for some help.
Hope I didn't miss anything obvious
You can use the 'now' attribute,
$today = new DateTime('now'); to get the current time.
Don't forget to set your timeregion in your php.ini to be able to get the right time.
And if you want to compare them, you can use date_diff and then
$var->format('%r') to get the value.
%r is going to be empty if the result is positive.
Good luck!

PHP DateTime::createFromFormat DATE_ATOM ISO 8601

I am using PHP 7.2, and trying to create a date from a string as follows:
$dateString = '2018-12-31T01:01:01+00:00';
$converted = DateTime::createFromFormat(DATE_ATOM), $dateString);
The snippet above works fine and returns the expected result.
The problem happens when I swap the day and month in the date string provided above, as follows:
$dateString = '2018-31-12T01:01:01+00:00';
$converted = DateTime::createFromFormat(DATE_ATOM), $dateString);
I was expecting this second example to return false, but instead I get an actual date time, 2020-07-12 01:01:01.000000.
So, I have no way of telling whether the second date was a proper date or not, because the system accepted it, and I will be saving in my database something which I shouldn't.
Could this be considered a bug in PHP 7.2?
Could this be considered a bug in PHP 7.2?
No, this is how the method is intentionally implemented. You can argue if it's the right way to implement it, but that's how it is. Notably even if we all agree that it's not right here, it will still keep working as it's implemented.
The practical answer here is to write a validator (for entirety of format and all parts) and run any untrusted input through it.

symfony3 datetime string in json object

My apologies in advance, if this has been answered before, I couldn't find the answer.
And also, i thought i fixed it, but it got unfixed for no appearant reason.
I have this code:
$date = new \DateTime('now');
$dateFormatted = $date->format(\DateTime::ISO8601);
$body->setDate($dateFormatted);
this should give me the current date and time in a string format, right?
after this, i pass the string to a json object, serialize it, and store it in the database (this works).
However, for some reason, the datetime object isn't formatted anymore, and is stored in an array like this:
{\"timezone\":{\"name\":\"+01:00\",\"transitions\":false,\"location\":false},\"offset\":3600,\"timestamp\":1518626336}
This breaks the rest of my functionality, as i want to store it in an object, and recreate a datetime object from it, whenever i fetch it again. I am clueless as to why this is happening. I am clearly formatting it to a string, or am i doing anything wrong? I've also tried clearing the cache, but that didn't do anything.
[EDIT] I've got a lot of answers from people telling me how to serialize an object to json format, this is not what i am looking for (as specified in my post). This is an example of a json serialized object containing a datetime array in my database, instead of a datetime string: (it is basically a message with a type, date, targetdate and messagetext)
"{\"type\":0,\"date\":{\"timezone\":{\"name\":\"+00:00\",\"transitions\":false,\"location\":false},\"offset\":0,\"timestamp\":1518638298},\"targetDate\":{\"timezone\":{\"name\":\"+01:00\",\"transitions\":false,\"location\":false},\"offset\":3600,\"timestamp\":1518638280},\"status\":0,\"messageText\":null}"
What I am trying to achieve with $dateFormatted = $date->format(\DateTime::ISO8601); is a string, that i can store in that object.
but what i am getting is an array.
i'm beginning to think that the ->format() functionality is broken.
I am not sure about how you are serializing the DateTime Object.
when you serialize the DateTime Object it can become like this only.
what you need to do is when you fetch the data from the database, you need to unserialize it, There you will get a DateTime Object
json_encode(new DateTime('#1419237113'));// serialize
json_decode(/*fetch data from db*/);// unserialize
I recommend you to use PHP Serialize method is you want to store an Object in database.
You must serialize the DateTime object ($date = new \DateTime('now');) before saving it in the database.
Example:
$date = new \DateTime('now');
$serialized_date = serialize($date);
$serialized_date can be stored as String.
Then when you retrieve the serialized DateTime, you can format the DateTime as you want. Before formatting you must unserialize the retrieved String.
Example:
$unserialized_date = unserialize($serialized_date);
echo $unserialized_date->format('Y-m-d H:i:s');
echo $unserialized_date->format(\DateTime::ISO8601);
I think i have answered my own question. Instead of passing the formatted DateTime object to my setter, i formatted it in my setter itself. for some reason this works... after that, when i want to get it back out. i make sure to pass it out as a string, rather than a datetime object. I don't know why, but using format, serialize, or normalize outside my getter does nothing and passes an array to the setter.

Laravel5 Eloquent default date mutator fails with JSON date input

I've a model with date mutators, such as created_at. Let's say a generic timestamp property.
When passing data from the client in JSON format, i'll get
{
timestamp: "2016-06-07T22:00:00.000Z"
}
That property will be used to set some model like so:
$model = new Foo();
$model->timestamp = Input::get('timestamp');
Since this will trigger the date mutator, php Carbon gets called and fails with
InvalidArgumentException in Carbon.php line 425
Unexpected data found.
Trailing data
Now, that's not an issue with Carbon itself, that is able to handle JSON formats. If you'll try
new Carbon('2016-06-07T22:00:00.000Z');
you'd infact get the expected result.
From what i see, the problem origins from a weird Eloquent behaviour. See this trace from the above mentioned InvalidArgumentException in Carbon.php line 425:
in Carbon.php line 425
at Carbon::createFromFormat('Y-m-d H:i:s', '2016-06-07T22:00:00.000Z') in Model.php line 2915
at Model->asDateTime('2016-06-07T22:00:00.000Z') in Model.php line 2871
at Model->fromDateTime('2016-06-07T22:00:00.000Z') in Model.php line 2826
at Model->setAttribute('timestamp', '2016-06-07T22:00:00.000Z') in Model.php line 3351
Eloquent is trying to createFromFormat passing a bad format which doesnt mirror the actual JSON format, that is causing the Carbon exception.
On the other hand, a simple call like the above mentioned new Carbon($jsonDate) would work fine in this case.
How should i approach to solve this?
Isn't this supposed to be an Eloquent bug?
== EDIT ==
I didn't code any mutator myself. I'm using default date mutators like so:
public function getDates() {
return ['timestamp'];
}
Eloquent analyses the date you give it, when the attribute is set in the getDates function.
In it's analyses it has four steps: (see Modal.php asDateTime method for clarification, the code is pretty well commented: https://github.com/illuminate/database/blob/master/Eloquent/Model.php#L2898)
If it is already a Carbon instance, use that
If it is an instance implementing DateTimeInterface, use that
If it is numeric, parse as a Unix timestamp
If it is a simple year month day format (tried by regex) use that
If none of the above, create a Carbon instance with the format you specify as default
In you case, 1-4 don't match, so it tries 5.
You have no custom dateFormat specified on the model, so it uses the default date format applicable to the type of database connection you are using. You can override this by adding a $dateFormat variable to the model:
protected $dateFormat = 'U';
But your normal timestamps are probably in the correct format already. So this solution would not work for you.
In your case I would just do:
$model->timestamp = Carbon::parse(Input::get('timestamp'));
Or use Carbon::createFromFormat() with the appropriate format.
I don't exactly know why they don't just parse it with Carbon directly. I guess it is more error prone and less controllable. With different international formats you might get an unexpected outcome (month and day switched etc). It might also be slower than their current approach.

How to format a getUpdatedAt() kind of date in Symfony?

I'd like to change the formatting of a date in Symfony 1.4
The default one being:
<?php echo $question->getUpdatedAt();
// Returns 2010-01-26 16:23:53
?>
I'd like my date to be formatted like so: 26/01/2010 - 16h23
I tried using the format_date helper DateHelper class.
Unfortunately the API is rather empty (something really needs to be done about it.)
Browsing the helper's source code, I found that a second argument, format, can be passed.
I assumed it was using the same syntax as PHP's date function.
But here's what it outputs (same example as above):
<?php sfContext::getInstance()->getConfiguration()->loadHelpers('Date');
// [...]
echo format_date($question->getUpdatedAt(),'d/m/y - H\hi')
// Returns 26/23/2010 - 16\4i
I'm sure I'm not the first one having trouble doing this but I've been Googling around and nothing accurate showed up.
Do you guys have any idea how to format a date in Symfony 1.4?
Have a look at the new functions in 1.4.
You can do:
$question->getDateTimeObject('updated_at')->format('d.m.Y');
// I assume the field's name is 'updated_at'
From the docs:
Date Setters and Getters
We've added two new methods for retrieving Doctrine date or timestamp values as PHP DateTime object instances.
echo $article->getDateTimeObject('created_at')->format('m/d/Y');
You can also set a dates value by simply calling the setDateTimeObject method and passing a valid DateTime instance.
$article->setDateTimeObject('created_at', new DateTime('09/01/1985'));
But it seems only to work for Doctrine.
How bout going with the default PHP date function? date('d/m/Y', strtotime($question->getUpdatedAt())
You can use also sfDateFormat class to work with dates.
link text
do you try :
echo $question->getUpdatedAt('d/m/y - H\hi')
I think it's the easiest way

Categories