DateTime.MaxValue saves as Zero in mysql - c#

I am using C# and MySql. I have a requirement where I need to save DateTime.MaxValue to one of the column.
ADO.NET code gives me below value for DateTime.MaxValue
12/31/9999 11:59:59 PM
When I save this in mysql, I see that the value for that datetime(3) column is saved as:
0000-00-00 00:00:00.000
Sample ADO.NET Code
DateTime time = DateTime.MaxValue;
sqlCommand.Parameters.AddWithValue("Expires", time);
sqlCommand.ExecuteNonQuery();
DataType of the column is datetime(3)
I still cannot figure it out why DateTime.MaxValue is saved as 0000-00-00 00:00:00.000
Any thoughts around this?

A DATETIME column can store values up to '9999-12-31 23:59:59'. DateTime.MaxValue is actually 9999-12-31 23:59:59.9999999. When you try to insert it, the fractional seconds overflow the maximum size of the field.
Normally (in STRICT mode), MySQL Server would issue a datetime field overflow error. But if you're running your server in ANSI mode, the overflow is silently converted to the "invalid" date time value 0000-00-00.
One way to fix this problem is to use STRICT mode in your MySQL Server.
Another way is to specify the column type as DATETIME(6), which allows the fractional seconds to be stored.
A third way is to truncate the fractional seconds from your DateTime objects in C# before inserting them in the database.

Maybe some trigger prevents from saving such a high date to your column?
Have u tried inserting that date from SQL query ?
I did some tests in Oracle DB, and all went smoothly.
It shouldnt be different in mysql ...

Related

Inserting DateTime to SQL script

I'm writing a SQL script to register components in a database. One of these requires DateTime (from last year) to be inserted as one of the values into a table, like this:
INSERT INTO ComponentTable (ComponentId, Setting, [Value]) VALUES ('id', 'StartDate', ... )
The C# I had previously been using to insert the value was DateTime.Today.AddDays(-365).ToString() (before switching to a database).
Is there a way of adding the same thing into the SQL script above?
Thanks
This article shows and explains the SQL Server date/time functionality you need:
Date and Time Data Types and Functions (Transact-SQL)
In your case, this might work:
INSERT INTO ComponentTable (ComponentId, Setting, [Value]) VALUES ('id', 'StartDate', DATEADD(DAY, -365, GETDATE()))
Note the following:
Previously, you determined the date/time value in your client app (C#), thus using the date/time value of your client computer. When using the SQL Server functionality, the system date/time of the machine running your SQL Server instance will be used instead. (I consider this to be an advantage.)
It is advised to store date/time values in the database in a way that they are not region-specific. So including the time zone might be important if you have multiple clients in different time zones. In my opinion, storing the UTC date/time values in the database (by using GETUTCDATE() instead of GETDATE() and converting the retrieved value in your C# client apps to local time (using the DateTime.ToLocalTime() function) might be useful.
I tried the following, this gives you the date 365 days ago; is this what you want?
CREATE TABLE test (ID serial PRIMARY KEY, startdate DATE);
INSERT INTO test (startdate)VALUES (date(now()) - integer '365');
See the docs: https://www.postgresql.org/docs/9.0/functions-datetime.html#FUNCTIONS-DATETIME-EXTRACT
If you want exactly one year (taking care of leap years) then you would probably need to use 'extract' to get the year, then subtract one, and reconstruct the date.

Convert C# Datetime to 0000-00-00 00:00:00 to MySQL

DateTime field is 'not null' in Table Structure but I want to store data (MVC C# Datetime) 0000-00-00 00:00:00 to MySQL Table without changed table structure.
I Try to do this but its but ERROR!!
Convert.ToDateTime("0000/00/00");
Please HELP , Thanks
The minimum value for .NET DateTime is January 1, 0001; the minimum for MySQL DATETIME is '1000-01-01', but in case of SQL MODE it is possible to insert '0000-00-00' as DATE, see NO_ZERO_DATE in documentation.
If you want to store '0000-00-00' in .NET DateTime structure, then use '0001-01-01', then if it is possible change this value in representation layer.
If you want to store '0000-00-00' in MySQL, then you should check SQL MODE in MySQL server -
SELECT * FROM information_schema.GLOBAL_VARIABLES
WHERE VARIABLE_NAME = 'sql_mode';
From documentation: NO_ZERO_DATE - In strict mode, do not permit '0000-00-00' as a valid date. You can still insert zero dates with the IGNORE option. When not in strict mode, the date is accepted but a warning is generated.
Server SQL Modes
You need to insert those values as string
Like this
Create table tbl(dt datetime);
Insert into tbl values('0000-00-00 00:00:00');
SELECT CAST(dt as char) FROM tbl
Fiddle
If you're asking how to create a C# DateTime object with 0000-00-00 00:00:00 - you can't, it's an invalid date. You could use DateTime.MinValue though. From memory that's 0000-01-01 00:00:00
Why not use NULL? Using magic values instead of NULL is not always a good idea.

Default getdate() always stores AM for time in SQL Server

I have default value getdate() in the blog table in SQL Server database
In fact, I am not even sure if it does store AM or PM in the field
The column date_created is of type datetime and default value is (getdate())
how can I store AM or PM in the field?
The database is not storing AM or PM... it is storing a specific point in time. How you represent that point in time visually (through 24-hour time or 12-hour time) is up to how you do your formatting.
The column date_created is of type datetime
That means it's stored as a binary value that is agnostic about AM/PN and 12/24 hours. All that only happens when you ask for a string representation.
So it could be just the configuration of your App or tools.
Try something like this:
SELECT CONVERT(VARCHAR(20), GETDATE(), 100)
That will yield "Nov 21 2011 1:29PM". See here for more formats.

C#+linq - Inserting DateTime value to the Db in the right format

I have a Db server with DateTime fields in the format of "yyyy-MM-dd mm:hh:ss"
I'm trying to use linq2sql to insert a DateTime member to a DateTime field in one of my tables.
When I do it in SQL I convert the DateTime as following:
"Insert into .... Convert(datetime, getdate(), 120) ..."
But when I try to submit the object from Linq the date time inserts in the wrong format.
Is there a way to define the format that will be inserted to the Db in Linq?
Or is it a DateTime object Issue?
You shouldn't be dealing with a string format when you pass dates and times to the database, any more than you would if you were passing a number. The database should be handling all this for you without any conversions. This is true whether you're using LINQ or within the SQL - almost any time you have to manually do string conversions between types at the database level, you should look for a better solution.
If you read the value back out of the database (as a DateTime again) does it have the right value? If not, in what way is it wrong?

System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow

I am working with C#.net and also SQL Server 2008.
I have the following error, when trying to run a test unit within my project.
System.Data.SqlTypes.SqlTypeException:
SqlDateTime overflow. Must be between
1/1/1753 12:00:00 AM and 12/31/9999
11:59:59 PM..
Database Table
Column Name: createddate
Type: datetime
Default Value: (getdate())
Allow Nulls: No.
I don't want to insert the createddate as part of my INSERT query.
When I manually enter some data into the database table I get the following error:
The row was successfully committed
to the database. However, a problem
occurred when attempting to retrieve
the data back after commit. Because
of this the displayed data within the
row is read-only. To fix this
problem, please re-run the query.
I don’t understand why I am getting this error and cannot find anyone who has had this problem. Can anyone help?
Matt is most likely on the right track. You have defined a default value for your column - however, that will only take effect if you actually insert something in your table in the database.
When you do a unit test, as you say, you most likely initialize the DateTime variable to something (or not - then it'll be DateTime.MinValue, which is 01/01/0001) and then you send that to the SQL Server and this value is outside the valid range for a DATETIME on SQL Server (as the error clearly states).
So what you need to do is add a line to your .NET unit test to initialize the DateTime variable to "DateTime.Today":
DateTime myDateTime = DateTime.Today
and then insert that into SQL Server.
OR: you can change your SQL INSERT statement so that it does not insert a value for that column - it looks like right now, it does do that (and attempts to insert that - for SQL Server - invalid date into the table). If you don't specify that column in your INSERT, then the column default of getdate() will kick in and insert today's date into the column.
Marc
Are you using Linq to SQL to write your unit test?
If you are, it might be bypassing the getdate() default value, and using some other value instead which falls outside the valid range.
I got the same issue, I was using Linq with the DataClasses files automatically generated by VS2010.
The I realised that Linq is not using the default value (GetDate()) but it will send a Datetime.Min value. As the consequence the SQL server will reject this datetime "01/01/0001" because it's not in range.
What I did to fix it is to always set the value to Datetime.Now or Datetime.Today and so Linq will not send the bad Min Datetime value anymore.
You are probably getting an overflow error in your unit test because you are passing in an uninitialised DateTime with the value DateTime.MinValue which is outside the allowable range for SQL's datetime.
I think I have seen that error message when modifying the table manually, it isn't a problem, just refresh the table.
are you using a data context class setup with the DBML file and all that jazz? If so, then you can click on the field in your DBML file and set the "Auto Generated Value property" to True. Visual Studio must already know to do this with the Pkey fields, but has to be set for these "timestamping" sort of actions

Categories