MySQL Invalid datetime format - mysql

I got this error when I'm trying to insert the value 2016-03-27T03:15:51.213 to the column with the data type 'timestamp' in my Yii1 app:
exception 'CDbException' with message 'CDbCommand failed to execute the SQL statement: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2016-03-27T03:15:51.213' for column 'created' at row 1.
The strangest thing, when I try to insert a 2016-03-27T13:15:51.213 value - everythin's ok. What's wrong?
I use OpenServer on my Windows machine with PHP 5.6 and MySql 5.7

Finally I've found the solution. The reason of the problem was on my Windows machine. I had an active option "Automatic transition to winter and summer time".
So, because of this option my computer didn't know about time between 3AM and 4AM when the timezone changes, because when the option is turned on, the given time does not physically exist))) So simple)
When I turned off this option on my PC and reboot it, the message had disappeared from logs.
BTW: this problem won't appear at PCs with Linux and UTC-settings without automatic transitions to winter and summer time.
Hope my answer will be helpful for somebody.

Do something like this. First create a datetime object from the string datetime
$datetime = date("Y-m-d h:i:s", strtotime("2016-03-27T13:15:51.213"));// Output = 2016.03.27 01:15:51
And then use this $datetime in the sql query.

Related

Lumen show different time than what is saved is MYSQL DB

my current timezone is Asia/Karachi and when i retrieve table data from mysql it gives me (actual time - 5 hours)
for eg:
mysql column value: '2021-04-21 01:34:57'
and when i retrieve from laravel DB::table('table_name')->get()->toArray();
it gives following :2021-04-20 20:34:57
and changing my timezone doesn't change anything either.
so is there something else i'm missing ?
btw i created following route for checking my current timezone
$app->get('/timezone', function () {
return date_default_timezone_get();
});
and it gives same what is saved in my env i.e(Asia/Karachi) but this doesn't change the result i get from mysql even if i change it to some other timezone like Asia/Kolkata.
I tried researching on this but didn't get any suitable answer.
i tried alot of things to solve this issue like
adding env variables APP_TIMEZONE="Asia/Karachi" (did not work)
also i tried adding DB_TIMEZONE="+05:00" (this worked in my local but not on stagging)
finally i saw somewhere that someone else had exact same issue resolving this and he did it by adding the hours using carbon which also worked for me
'posted_at' => Carbon::parse($record->posted_at)->addHours(5)->toDateTimeString(),
i know this is not the optimal solution but this was the only solution that worked so i had to go with it.
https://dev.mysql.com/doc/refman/8.0/en/datetime.html
If you store a TIMESTAMP value, and then change the time zone and retrieve the value, the retrieved value is different from the value you stored. This occurs because the same time zone was not used for conversion in both directions. The current time zone is available as the value of the time_zone system variable.
As far as I know, you have a couple things to consider:
The timezone of your Laravel/Lumen app
This can be found found in config/app.php -> timezone.
The timezone of your MySQL server
You can retrieve this using:
mysql> SELECT ##global.time_zone, ##session.time_zone;
The timezone of the server itself
If the mySQL query above returns SYSTEM, it means it uses the system timezone setting, which for Debian/Ubuntu etc you can check using:
cat /etc/timezone
From my experience, you can most often leave the system/mySQL timezones intact and only set the correct timezone in your Laravel config. I know it caused me a headache the first time I had to figure out how this actually worked.

MySQL datetime field - can't write date

There is one table with datetime field set to allow nulls.
I am unable to enter any date format in this field as I tried this:
"2011-01-01 00:00:00"
"0000-00-00"
"21.01.2013"
and many others but al of the report error:
Microsoft Visual Studio
---------------------------
Invalid value for cell (row 1, column 3).
The changed value in this cell was not recognized as valid.
.Net Framework Data Type: MySqlDateTime
Error Message: Invalid cast from 'System.String' to 'MySql.Data.Types.MySqlDateTime'.
Type a value appropriate for the data type or press ESC to cancel the change.
What can I do ?
EDIT: Above problem occurs when I directly enter data in mysql table using VisualStudio - ServerExplorer. If I open MySQL workbench then there is no problem and I can write date in format "2011-01-01 00:00:00". Why VS treats Mysql DB differently than Mysql Workbench ?
And here is what I am trying to do from the code
Private Sub DataGridView1_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
Debug.Print(e.ToString)
If e.ColumnIndex = 3 Then
DataGridView.Rows(e.RowIndex).Cells(3).Value = "2011-01-01 00:00:00" 'entering this test value does not work
End If
End Sub
I had similar issue migrating from old code in Java. Code tried to save "2011-01-01 00:00:00" to DATE field in database. It worked when I removed time, and was saving date only as "2011-01-01".
Originally I went through that issue setting development environment under Windows. Given project was entirely developed under Linux and it worked fine with default instance of MySQL in Linux. By surprise it didn't work with default database instance under Windows. I tried to find out what can be different, but gave up, as changing code was easier, and worked fine.

Setting default-time-zone on MySql Server via PhPMyAdmin

I have a shared hosting mySql instance which has it's system_time_zone set to Pacific Standard Time and it's time_zone variable set to System, hence effectively it's running on Pacific Standard Time.
i.e. I've run the following command to find this out:
SELECT version( ) , ##time_zone , ##system_time_zone , NOW( ) , UTC_TIMESTAMP( )
I would like to change the default mySql database / local mySql DB time-zone to GMT/UTC time. I tried to run, SET time_zone = '+0:00', and this does execute successfully!
However, this does not seem to affect the time_zone variable, when I check the state of ##time_zone. I've looked at another post dealing with similar issue How to set MySQL to use GMT in Windows and Linux and I also checked the MySql documentation, with little progress. Since I am on a shared-hosting solution, I have limited access and I don't have access to more than what my PhPMyAdmin mySql functionality has on offer.
I wonder if there is any way to change the default_time-zone from within an SQL query, or do I need to fall back to the command line (to which I don't have access to, unfortunately).
Thanks for your help and advice,
Martin
In short, MySQL actually stores 'datetime' data type fields internally as UTC.
However, PhpMyAdmin shows you the dates using the server default time, hence your confusion.
For example, try adding this line before your SQL statement in PhpMyAdmin:
SET ##session.time_zone='+00:00';
SELECT * FROM MY_TABLE
See the MySQL documentation for further details, or the answer in this post: How to correctly set mysql timezone
Cheers
Matt
For shared hosting, you have to ask support-guys to help you and change default time zone for you? I had similar problem with Arcor hosting-provider, called them and they fixed it. Before that, I found temporary solution in date_default_timezone_set() from PHP code. Probably the best solution is to ask someone who has privilege to change that parameter.
<?php
date_default_timezone_set('UTC'); //define local time
$date=date('l jS \of F Y h:i:s A'); //type of time shown
$conn=mysql_connect("localhost","root","") or die('Could not connect!'); //your database connection here
$db_selected = mysql_select_db('databasename', $conn); //select db
$result=mysql_query("INSERT INTO table (date) VALUES ('$date')", $conn);
?>
Simply sent the time as VARCHAR into db hope it helps and sorry for syntax errors (if there are any).

Mysql "Time" type gives an "ArgumentError: argument out of range" in Rails if over 24 hours

I'm writing a rails application on top of a legacy mysql db which also feeds a PHP production tool. Because of this setup so its not possible for me to change the databases structure.
The problem I'm having is that two table have a "time" attribute (duration) as long as the time is under 24:00:00 rails handles this, but as soon as rails comes across something like 39:00:34 I get this "ArgumentError: argument out of range".
I've looked into this problem and seen how rails handle the time type, and from my understanding it treats it like a datetime, so a value of 39:00:34 would throw this error.
I need some way of mapping / or changing the type cast so I don't get this error. Reading the value as a string would also be fine.
Any ideas would be most appreciated.
Cheers
I'm not familiar with Rails so there can be a clean, native solution to this, but if all else fails, one workaround might be writing into a VARCHAR field, then running a 2nd query to copy it over into a TIME field within mySQL:
INSERT INTO tablename (name, stringfield)
VALUES ("My Record", "999:02:02");
UPDATE tablename SET datefield = CAST(stringfield as TIME)
WHERE id = LAST_INSERT_ID();

The Generation Time is wrong when pint in phpMyAdmin

I using phpMyAdmin 4.4.14 in Win7+Chrome and MySQL 5.6 in Linux.
My timezone is +8
The date command in Linux returns a correct date and time.
When I issue select now() inside the phpMyAdmin, the date and time is correct.
But, when I print the result, the time value in the Generation Time is wrong.
Look like that the Generation Time does not do a +8 to the hour.
How to fix ?
Cheers,
Alvin SIU
Print view is done via PHP script, so the issue is in PHP, not in MySQL. In order to change this timestamp, you need to open php.ini and to change/add date.timezone variable with desired value:
[Date]
; Defines the default timezone used by the date functions
; http://php.net/date.timezone
date.timezone = "Europe/Paris"
All available timezones can be found here:
http://www.php.net/manual/en/timezones.php