Saving Carbon from string to MySQL - php

I'm having trouble saving a timestamp to my MySQL database. In this case, the user writes a date in a text field, with the format dd/mm/yyyy, and I want it to be saved as a timestamp.
The problem is, it is always complaining about incorrect format.
So far, I've tried:
$d = DateTime::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");
// or
$d = Carbon::parse($request['b_date']);
// or
$d = Carbon::createFromFormat("d/m/Y H:i:s", $request['b_date'] . " 00:00:00");
// so that I can
$p->b_date = $d;
But it never lets me save it.
Here's the log:
[2019-05-29 15:14:02] local.ERROR: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1111-11-11 00:00:00' for column 'b_date' at row 1 ...
I've been trying to do this for hours. What am I missing?
And how can '1111-11-11 00:00:00' be an invalid datetime value?

Declaring the datatype as DateTime in the migrations script worked for me.
...
Schema::create(...
$table->dateTime('b_date'); // use dateTime instead of timestamp
...
Setting it with carbon in the controller:
...
$p->b_date = Carbon::createFromFormat("d/m/Y H:i:s", $input['b_date'] . " 00:00:00");
...

Related

How to make a datetime a bigint?

I want to convert a datetime to big int. For Example. I have an entry in the file that i read in php like normal datetime, "2021/05/20 11:46"(i keep it in a variable named $data) that i want to transform into a bigint like 202105201146 (year+month+day+hour+minute) . I tried to work around and make it working, but I still get the error :
"Argument #2 ($timestamp) must be of type ?int, string given in". >
The line in question is :
$ID= date('Y', $data) . date('m', $data) . date('d', $data). date('G', $data) . date('i', $data). date('s', $data);
You must first convert it into a datetime object, and then format it as "bigint":
$dateAsString = '2021/05/20 11:46';
$datetime = \DateTime::createFromFormat('Y/m/d h:i', $dateAsString);
echo $datetime->format('Ymdhi'); // 202105201146
However, since the error is asking for a timestamp (as int value), it could be better to use the getTimestamp() method of DateTime class, which returns the epoch timestamp:
$dateAsString = '2021/05/20 11:46';
$datetime = \DateTime::createFromFormat('Y/m/d h:i', $dateAsString);
$timestamp = $datetime->getTimestamp(); // 1621511160

Unable to save the exact timestamp from form

I'm trying to save events into my table that contain date_start and date_end timestamps. From another PHP page, I get four inputs: two date inputs and two time inputs. I'm trying to insert these values but I keep getting the following value on inserting it:
0000-00-00 00:00:00
Here's my script:
$rep=$bdd->query('SELECT * FROM association WHERE nom="'.$_SESSION['usertag'].'"');
$data=$rep->fetch();
$debut="\'".$_POST['date_start']." ".$_POST['time_start'].":00\'";
$fin="\'".$_POST['date_end']." ".$_POST['time_end'].":00\'";
$debut=date('Y-m-d H:i:s');
$fin=date('Y-m-d H:i:s');
$timestamp_debut =strtotime($debut);
$timestamp_fin = strtotime($fin);
$req=$bdd->query('INSERT into evenement values (NULL,'.$_POST['name'].','.$_POST['content'].',\''.$timestamp_debut.'\',\''.$timestamp_fin.'\','.$data['id'].')');
PHP's strtotime() outputs a Unix timestamp. If your database column type is DATETIME, a Unix timestamp is not the correct format. You can just insert the formatted date() string.
For example:
strtotime(date('Y-m-d H:i:s'))
1562117846
date('Y-m-d H:i:s')
2019-07-02 21:36:40
For MySQL:
MySQL recognizes DATETIME and TIMESTAMP values ... [a]s a string in either 'YYYY-MM-DD hh:mm:ss' or 'YY-MM-DD hh:mm:ss' format. A "relaxed" syntax is permitted here, too: Any punctuation character may be used as the delimiter between date parts or time parts. For example, '2012-12-31 11:30:45', '2012^12^31 11+30+45', '2012/12/31 11*30*45', and '2012#12#31 11^30^45' are equivalent.
String and Numeric Literals in Date and Time Context
However, it seems that you're using the current timestamp when you might want to use the values posted from your form. PHP's date() uses "the current time if no timestamp is given".
If you want to use your posted values instead, you can indeed use strtotime() to convert them to Unix timestamps and then date() to format them.
$date = '2019-07-02';
$time = '15:28';
date('Y-m-d H:i:s',strtotime($date.' '.$time));
2019-07-02 15:28:00
Alternatively, I might recommend using PHP's DateTime class:
$date = '2019-07-02';
$time = '15:28';
$datetime = new Datetime($date.' '.$time);
echo $datetime->format('Y-m-d H:i:s');
2019-07-02 15:28:00

Importing dates to MySQL

I cannot seem to find any info on this..
I need to convert a string to a date so that it will import properly to an SQL DATE field. When I import 12/25/2012 to the DB, it appears as 0000-00-00.
What's the proper way to do this?
Links and refs appreciated.
MySQL accepts dates in this format YYYY-MM-DD either change your date format 12/25/2012 to 2012-12-25 or modify them to match the correct format.
EDIT
If you want to continue using your own format try this
list($d,$m,$y) = explode("/", "12/25/2012"); //replace 12/25/2012 with your date
$hyphenDate = $y . '-' . $m . '-' . $d;
echo $hyphenDate;
As #Ravi pointed out in his answer, MySQL accepts dates in the format YYYY-MM-DD. Quoted from 11.1.5. Date and Time Types1:
Although MySQL tries to interpret values in several formats, date
parts must always be given in year-month-day order
For this, you can use str_todate()2 function to format it:
str_to_date('12/25/2012', '%m/%d/%Y);
SQL Fiddle Demo
This way, these input strings will be stored in your database as date objects(without any specific date format). Later, if you want to output these dates in a specific format you can use DATE_FORMAT3 to format it. Something like:
SELECT DATE_FORMAT(datefield, '%Y-%m-%d') FROM Test;
--2012-12-25
1, 2, 3: Links and refs, that you asked for.
Use class DateTime. Examples:
$SomeDate = new DateTime();
echo $SomeDate->format( 'Y-m-d H:i:s' ); //Must be MySQL compatible (YYYY-MM-DD)
$ThisDate = new DateTime( date( 'Y-m-d H:i:s' ) );
echo $ThisDate->format( 'Y-m-d H:i:s' ); //Must be MySQL compatible (YYYY-MM-DD)

PHP/MySQL - preparing string in a right format for inserting in a datetime SQL column

In my UI the dates are shown like this - dd.mm.YYYY hh:ii:ss. The users are able to edit/add new dates and most probably they'll try to use the same format (24.06.2012 15:35:00) which can not be used for a SQL query. Here is what I've done till now:
$dt = (date_parse_from_format("d.m.Y H:i:s", $data['event_time']));
$newdate = sprintf("%02d-%02d-%04d %02d:%02d:%02d" , $dt['day'], $dt['month'], $dt['year'], $dt['hour'], $dt['minute'], $dt['second']);
$test = date("Y-m-d H:i:s", strtotime($newdate));
if ($test == "1970-01-01 01:00:00")
{
throw new Exception('Invalid date');
}
What happens is - if I leave the check if ($test == "1970-01-01 01:00:00") I get an exception, but if I comment the $test = date("Y-m-d H:i:s", strtotime($newdate)); line and the check the date is inserted only with zeros.
$newdate is a sting in the right format for SQL - YYYY-mm-dd H:i:s but obv. I miss something here. How to insert this string as a valid SQL datetime?
Thanks
Leron
The DateTime class was introduced in PHP 5.2 and would allow you to use something like this
$dt = DateTime::createFromFormat("d.m.Y H:i:s", $data['event_time']);
if($dt === false){
throw new Exception("Invalid date");
}
DateTime::createFromFormat returns false on failure (This method is only available since PHP 5.3)
Then when saving to the database you can use the following to get the correct format for MySQL
$dt->format("Y-m-d H:i:s")
MySQL provides the FROM_UNIXTIME( ) and UNIX_TIMESTAMP( ) functions to convert a Unix timestamp to a MySQL date format, and vice versa.
$SqlString = "INSERT INTO table(mydate, content) VALUES (FROM_UNIXTIME($mydate), $content)";
UNIX_TIMESTAMP, if called with no argument, returns a Unix timestamp (seconds since '1970-01-01 00:00:00' UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a DATE string, a DATETIME string, a TIMESTAMP, or a number in the
format YYMMDD or YYYYMMDD.
$SqlString = "SELECT *, UNIX_TIMESTAMP($mydate) AS mydate FROM table WHERE conId = $conId";
Take a deeper look at these MySql functions and also the mktime() function could help you.

date format in mysql?

Hello every one i have a problem with mysql dbms i never had a date storage in this format yyyy-mm-dd i always have it in this format dd-mm-yyyy i used this methode to change the date format while inserting data but it does not work
function dateConvert($dateInser) {
$dateTime = new DateTime($dateInser);
$dateFormate=date_format ( $dateTime, 'Y-m-d' );
return $dateFormate;
}
is there any solution ?
The DateTime constructor also expects specific formats, and I doubt dd-mm-yyyy is one of them. First parse your dd-mm-yyyy date to transform it into a DateTime object, and then format this DateTime object using the yyyy-mm-dd format :
$dateTime = date_create_from_format('d-m-Y', $dateInser);
$dateFormate = date_format($dateTime, 'Y-m-d');

Categories