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.
Related
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!
I am working with neo4j in PHP and I need to have a DateTime field that allows to store the time zone. If I save it as a string it is more difficult to make queries.
Add the timezone, and just output the string like this:
$x = new DateTime('2018-09-18 22:00:00', new DateTimeZone('Europe/Brussels'));
echo $x->format(DateTime::W3C);
Which gives you:
2018-09-18T22:00:00+02:00
When you pull your time from the DB, you can now create the object like this:
DateTime::createFromFormat(DateTime::W3C, $row['your_date_column']);
Play with it here: https://3v4l.org/DQjJO
I've got a variable declared like such: $var = new DateTime(null);.
I want to change the time that echo $var->format('g:i A'); outputs.
I want to achieve this solely by using a time string such as 07:30:28.
How can I do this without re-creating a DateTime object ($var) each time? I can't think of a way to achieve this.
DateTime::modify() will do exactly what you want. It will quite happily accept a time in string format and apply it to the object:-
$date = new \DateTime();
$date->modify('07:30:28');
See it working.
Alternatively, you can do it all in one go:-
$date = (new \DateTime())->modify('07:30:28');
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');
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