Laravel: saving date to MySQL - php

In my controller, when I create an event, it saves perfectly fine. The user enters a date in dd-mm-yyyy and it gets saved in MySQL DATETIME format. Then the details view renders it completely fine, just like the edit view via model binding.
As soon as I try to save from the edit form, the date somehow fails and returns 1970-01-01 00:00:00.
I am not really sure why this only happens on my update method, as my store method is in essence the same.
$input = Input::all();
$input['plannedTime'] = date('Y-m-d H:i:s', strtotime(Input::get('plannedTime')));
How comes the update method returns no error, validation is alright, but it still won't save it correctly?

The value of 'plannedTime' is a string of date format d-m-Y H:i:s.
There's your problem. PHP's strtotime does its best, but 04-05-2015 00:00:00 could be either April 5 or May 4, depending where you live.
As an example, on my install, strtotime('04-13-2014 00:00:00') fails (which'll get converted to 0, which'll get converted to 1970-01-01).
Laravel's date validation expects a value that strtotime can handle. If you're using an ambiguous date format, use createFromFormat to parse it, then format to spit it out in a more standard format.
$date = DateTime::createFromFormat('d-m-Y H:i:s', Input::get('plannedTime'));
$usableDate = $date->format('Y-m-d H:i:s');

MySQL never returns any error for invalid dates as far as i can remember, it just sets it to EPOCH and thats it!
You should enforce your dates to be always converted to a "Y-m-d H:i:s" format when communicating with your site and display the date in "d-m-Y" only on the output side.
You should try and use
public static DateTime DateTime::createFromFormat ( string $format , string $time [, DateTimeZone $timezone ] )
To create a datetime object from a format. If you know your format such as in this case, then provide the format and get a date object back which will be persisted correctly!

Related

Saving Y-m-d to Datetime to DateTimeImmutable field in Symfony

I want to save Y-m-d date format to field date
#[ORM\Column]
private ?\DateTimeImmutable $created_at = null;
When I save this formatted date:
$date = new DateTimeImmutable();
$date->setTimestamp($timestamp);
$date->format("Y-m-d");
Symfony saves with the following format:
2023-01-17 14:34:55
When I try to save a date like this:
$date = date("Y-m-d", $timestamp);
I get an error:
must be of type DateTimeImmutable, string given
What am I missing?
There are two problems that play a role here:
1: your entity expects an DateTimeImmutable Object, but you provide a string. Thus to solve this, use The DateTimeImmutable object to create and pass the correct object type your method asks for.
2: You want to save your date in a specific format, Y-m-d. To do that, change your ORM\Column type to date instead of dateTime
If you want to use Y-m-d format in your project, use the correct formatting to achieve that.
Take a look at the docs for deeper understanding.
To save the date in Y-m-d Format, you can use createFromFormat method
$date = DateTimeImmutable::createFromFormat("Y-m-d", date("Y-m-d", $timestamp));
I hope it will solve your problem. Let me know if you have any question

How to get timestamp format of a string date/time and return same format after some change in Carbon

I have a lot of variables of dates and times and I need to setTimezone in an abstract file. So I don't know anything about what is my times or dates format.
How I can keep the same format after changing the timezone? Or is there any way to find what is my date and time format?
For example, I have a timestamp like Y-m-d H:i and in my abstract class I'm changing the time zone by Carbon::parse($timestamp)->setTimezone($userTimezone) but with this line of code I'm losing my timestamp format and this code should convert multi-format of date and times. Another timestamp may have a format like Y/m/d H:I:s
I need something like this:
$format = Carbon::parse($timestamp)->getFormat(); // Returns 'Y-m-d H:i'
Or this can help; How I can setTimezone of a string timestamp without changing the format? date_default_timezone_get and date_default_timezone_set is not a good idea for this question.
You can simple change to:
Carbon::parse($timestamp)->setTimezone($userTimezone)->format('Y-m-d H:i');

The separation symbol could not be found Data missing

I'm working with Laravel 5.8 and I wanted to show a popup message if the UNIX timestamp of the current date is equal to the defined Unix timestamp of the popup.
So in order to do that, I added this at the Controller:
$date1= $popup->datep; // returns 1636403400
$date1 = Carbon::createFromFormat('Y-m-d H:i:s', $date1);
dd($date1);
But instead of getting the result of $date1, I get this error:
The separation symbol could not be found Data missing
So what's going wrong here? How can I solve this issue?
You are specifying a format that is clearly not an unix timestamp. Use method for the timestamp.
$date = Carbon::createFromTimestamp($popup->datep);
If you want to compare it to be the same date, you should do the following. I don't assume you want to compare it by the hour or second, that those will almost never match.
$date->startOfDay()->eq(now()->startOfDay());
Regarding Carbon Docs:
createFromFormat() is mostly a wrapper for the base php function DateTime::createFromFormat.
which is means that your second parameter must be a valid date/time format, not a timestamp.
The DateTime::create docs:
$datetime
String representing the time.
Instead, you need to use the createFromTimestamp instantiator.
$date1 = Carbon::createFromTimestamp($date1);

PHP: how to create date before the Epoch (1970) using Date instead of DateTime?

In my PHP script I've got a function handling birthdays like so:
$dateTime = \DateTime::createFromFormat('U', $time);
The problem is that this returns false with negative $time numbers (i.e. dates before 1-1-1970). In the PHP docs there's a comment saying that indeed
Note that the U option does not support negative timestamps (before
1970). You have to use date for that.
I'm unsure of how to use Date to get the same result as DateTime::createFromFormat() gives though. Does anybody have a tip on how to do this?
If you just need to format a UNIX timestamp as a readable date, date is simple to use:
// make sure to date_default_timezome_set() the timezone you want to format it in
echo date('Y-m-d H:i:s', -12345);
If you want to create a DateTime instance from a negative UNIX timestamp, you can use this form of the regular constructor:
$datetime = new DateTime('#-12345');

How to format date in PHP from a string of concatenated numbers?

I am new to PHP and I am trying to learn more of php date and time but I seem to get stuck with this.
I have this date format:
ddMMyyHHmmss
And an example is 120813125055 but I am trying to manipulate the string such that it will give me the format of:
yyyy-MM-dd HH:mm:ss (in the example above, 2013-08-12 12:50:55)
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
But it always gives me a result of 1969-12-31 18:00:00.
I assume that I need to do some string manipulation in PHP for this but I was wondering if there is an easier and more efficient way to do it?
I think what you're looking for is in the second response answered here: how to re-format datetime string in php?
To summarize (and apply to your example), you could modify the code like this.
$datetime = "120813125055";
$d = DateTime::createFromFormat("dmyHis", $datetime);
echo $d->format("Y-m-d H:i:s");
Use date_create_from_format:
$ts = date_create_from_format('dmyHis', '120813125055');
$str = date('Y-m-d H:i:s', $ts);
strtotime() only works on EASILY recognizable formats. Your is a ugly mix of garbage, so no surprise that strtotime bails with a boolean FALSE for failure, which then gets typecast to an int 0 when you tried feed it back into date().
And of course, note that your time string is NOT y2k compliant. two digit years should never ever be used anymore, except for display purposes.
You're using your function call and the argument the wrong way around.
In your example, php will try to return you the date for which the time is 'strtotime('120813125055')', and this function returns false (interpreted as 0). So you get returned the date formatted in 'Y-m-d H:i:s' for the Unix epoch.
You will need to get the actual timestamp of your string, so use http://www.php.net/manual/en/datetime.createfromformat.php.
You are mistaken here..
I tried to do something like:
date('Y-m-d H:i:s', strtotime('120813125055'));
You shouldn't use only numbers ( doesnt matter its an integer or a string ), than it will always give you the same thing.
You can use any other valid date and time ( E.G. 6 Jun 2013, 5 may 12...) . Because what strtotime() do is detect a valid date and convert it into timestamp.

Categories