I am using Laravel and I have to get some dates and store it on MySQL database.
When I create the date like this:
$date_sol = Carbon::createFromFormat("Y-m-d H:i:s","2020-12-10 01:00:00");
The date is properly stored on the database. However, I have to get the date from an input.
I am trying to get the date and then format it like this:
$novaData = $request->input('solicitacao_data') . ' 15:16:17';
$sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
However, I get the error:
DateTime::__construct(): Failed to parse time string (28/03/2020
15:16:17) at position 0 (2): Unexpected character
The error is at the line $sol->data = Carbon::parse($novaData)->format("Y-m-d H:i:s");
How do I make the formating conversion properly? I am new using Laravel. I am not sure about it.
For date format 'd/m/Y' try this.
Carbon::createFromFormat('d/m/Y', '22/02/2020')->toDateTimeString();
Similarly for date format Y-m-d try this
Carbon::createFromFormat('Y-m-d', '2020-02-22')->toDateTimeString();
output will be in format (Y-m-d H:i:s)
"2020-02-22 21:05:13"
Let's say you receive something as input.
Well, ideally you should first sanitize it, to make sure you received a string that can be interpreted as a date. For that, I would suggest you to have a look there :
php date validation
So, you assign the input to a var and append a string representing some time to it:
$novaData = $request->input('solicitacao_data'). ' 15:16:17';
From here, the easiest is to convert the string into a timestamp. Which can be achieved this way:
$time = strtotime($novaData);
And now, you can use Carbon to format the date the way you want :
$sol->data = Carbon::createFromTimestamp($time)->format("Y-m-d H:i:s");
Related
I have created the text box as well as the query for database.But in my case I want to fetch the data from input field and store it in database.
What actually happens is when I use the function $_POST['launch_date'] it displays the date that I add in db but when I store this in a variable and convert it to y-m-d format it doesn't give me the answer from the text field like $launch_date=date("Y-m-d",strtotime($_POST['launch_date']));.
when i print the both the above mentioned code in single line like echo $_POST['launch_date'] .$launch_date."<br>"; I get the following results
30/01/2020 1970-01-01.
The first one is from my text box and the second one is from the variable that I have created.
Use DateTime::create_from_format() to specify the format of your dates.
$launch_date = DateTime::create_from_format('m/d/Y', $_POST['launch_date'])->format('Y-m-d');
$_POST['launch_date'] = '30/01/2020';
$date = str_replace('/', '-', $_POST['launch_date']);
$launch_date = date('Y-m-d', strtotime($date));
echo $_POST['launch_date'] ." ".$launch_date."<br>";
Output: 30/01/2020 2020-01-30
The issue here is that the / has confused the format of m/d/Y (instead of d/m/Y). And if the date time is not valid (for instance, the month is greater that 12) is in the American format, you'll get the default time (aka UNIX timestamp 0) ie 1970-1-1.
You can create date from user input by
$launch_date = DateTime::create_from_format('d/m/Y', $_POST['launch_date'])->format('Y-m-d');
This is create a date variable of the form Year-Month-Date.
You can change the format as per your requirement.
Y-m-d is the standard date format for MySql.
If You are using PHP version 5.2 or lower you , you will have to parse the date in to 'd'. 'm' and 'y' . Then you will have to create a new date.
I have a controller action in which I fetch the currrent date like following:
$fullDate=date("Y-m-d");
$date = strtotime($fullDate);
$viewModel->setVariable("currentDate",$date);
// Here I would like to pass the variable to the View and then compare it with another date ...
With the method above I'm getting this when I do var_dump($currentDate);
int(1463587200)
which is not what I was expecting... I need a date in format like this 2016-05-19 (year-month-day)... How can I do this the valid way???
This strtotime is converting your formatted date into a Unix time-stamp. just remove it.
$fullDate=date("Y-m-d");
$viewModel->setVariable("currentDate",$fullDate);
you'll be able to compare two dates in this format Y-m-d without converting to time-stamp.
I have a calendar in html form and I want to insert this date into MySQL. The default MySQL date is 0000-00-00. But in my country the format is DD/MM/YYYY. So what to do to fix it. Thank you. I am using PHP.
You must use one format in your HTML page, and another format in your database.
So, if you want to store a date like this '12/05/2008' into mySql, you must transform it like this:
$date = '12/05/2008';
$dateToStore = date('Y-m-d', strtotime(str_replace('/','-',$date)));
And if you wonder why, you need to replace the '/' with '-' to make php know that the first part of the data string is the day, and then the month (as I think is your case).
MySQL the date format is always YYYY-MM-DD. To convert it to another format, you need to manually convert the retrieved date to the desired format like
$displayDate=date("d/M/Y", strtotime($mysqldate));
Method 1
You cant insert into DD/MM/YYYY format. Instead while rendering it in view file you can change into desired format.
<?php
$date = $result['db_date']; // I ASSUMED YOUR DB FIELD IS db_date
$desiredFormat = date('d/m/Y', strtotime($date)); // CONVERTING INTO YOUR FORMAT
echo '<pre>'; print_r($desiredFormat); // DISPLAYING IT
?>
Method 2
You can retrieve from database in your desired format using below
SELECT *, DATE_FORMAT(YOUR_DATE_FIELD, "%m/%d/%Y") AS date FROM YOUR_TABLE;
Use MySQL STR_TO_DATE
Try this mysql query :-
INSERT INTO `table`(`date`) VALUES (STR_TO_DATE('10/10/2015', '%d/%m/%Y'))
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!
So I have a problem. Trying to convert input from form text input field which is in the following format: 08/06/2013 to a value that can be inserted into mysql datetime column.
I have tried this
$startdate_timestamp = strtotime($this->startdate);
// $this->startdate is the value from the input field
$this->startdate = date("YYYY-MM-DD HH:MM:SS",$startdate_timestamp);
But it seems that it is not doing anything. Is there any other way than this that would work ? I am using Yii framework so that is why code looks weird :)
strtotime() is smart, but it's not psychic or a genius, and when it screws up, it screws up bigtime. Don't use it, especially with ambiguous formats like m/d/y. There's no guarantee it won't be treated as as d/m/y.
Use date_create_from_format() instead, which lets you explicitly specify the input format. This is far more reliable, since you'll be in control over how the d and m portions are handled:
$ts = date_create_from_format('m/d/Y', '08/06/2013');
$start_date = $ts->format('Y-m-d H:i:s');
Do it on insertion using MySQL query superpowers. PHP date functions are a PITA: INSERT INTO FOO (date_field) values (DATE_FORMAT($this->startdate, '%Y %M %D')); Hope that helps!
$this->startdate = date("Y-m-d H:i:s", strtotime($this->startdate));
This will put it in the YYYY-MM-DD HH:MM:SS format compatible with MYSQL.