I'm trying to save date in yyyy-mm-dd format instead of yyyy-dd-mm format to my database. I added
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
to the model class, but result didn't change. Date is still yyyy-dd-mm format in database.
Is it necessary doing it with C# code I can't change anything in database table. How can I do that ?
Dates in a (relational) database should be stored in a datetime column, or the equivalent for whatever flavour of database you are using (SQL server documentation). You can choose any format to display the date in your application, that has no bearing on how is stored.
If you're storing the dates in a database in a text format, you are storing up a world of pain that will come back to hurt you later on.
If your column is a string column, you should change it and use a date column as MarcE mentionned.
But, according what I understood, you have a Date column and you want to change the format.
In sql server date is not store like a string.
And the format that you see is associated the collation of your database.
If you want to change it, you should try to change date format of your db.
-- Set date format to day/month/year.
SET DATEFORMAT dmy;
GO
DECLARE #datevar datetime2 = '31/12/2008 09:01:01.1234567';
SELECT #datevar;
GO
-- Result: 2008-12-31 09:01:01.123
SET DATEFORMAT dmy;
GO
DECLARE #datevar datetime2 = '12/31/2008 09:01:01.1234567';
SELECT #datevar;
GO
-- Result: Msg 241: Conversion failed when converting date and/or time -- from
character string.
GO
https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15
Related
I have a SQL Server database, one of my tables LatestData has a column which is a non-nullable DATETIME, with a default value of 01/01/1970. See code below the the exact T-SQL code for this column.
[MyDateTime] DATETIME DEFAULT (CONVERT([DATETIME], CONVERT([DATE], '1970/01/01 00:00AM', (0)), (0))) NOT NULL
When this table is added into our server code (C#) via an .EDMX data model, the field looks like the following:
public System.DateTime MyDateTime { get; set; }
I add new data to this table through C#, but at the time of adding the row, my MyDateTime column does not have any data.
As the column is Not Null, my MyDateTime field is set to 01/01/0001 automatically.
Trying to add this date to my DateTime column throws the following error:
System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
After doing some research I found that C# Datetime MinDate is 01/01/0001, whereas SQL Server DATETIME's mindate is 01/01/1753 and this is causing the error.
The C# code is passing the 'empty' field as 01/01/0001 to the database which is then trying to convert it. This is obviously unsuccessful.
Is there any way for the database to know to revert to the default value instead of trying to convert the DATETIME firstly, or do so if a conversion fails?
I know that I could set the column in the Datatable to be a DateTime2 or specify a date for this column before adding it via C#, but that doesn't seem like the best way to go about it?
Thanks in advance for any help.
If 1970-01-01 is an acceptable no date set to you, then put it in the C#:
public System.DateTime MyDateTime { get; set; } = new DateTime(1970, 1, 1);
I do think you should consider allowing nulls in the column though, and make it:
public System.DateTime? MyDateTime { get; set; }
You asked for a SQLS-only fix; the only one I can think of right now is to use a stored procedure to do your insert:
--set up an example table with a datetime
create table a(a datetime);
--test that an insert doesnt work out
insert into a(a) values(cast('0001-01-01' as datetime2)); --error!
go
--make a procedure to do the insert logic/conversion
CREATE PROCEDURE a_ins(#a DATETIME2)
AS
BEGIN
INSERT INTO a (a)
--if the date is less than the column will support, default it
SELECT case when #a < CAST('1753-01-01' as datetime2) THEN cast('1970-01-01' as datetime) else cast(#a as datetime) end
END
GO
--quick run the procedure to test
DECLARE #dt2 DATETIME2 = cast('0001-01-01' as datetime2);
EXEC a_ins #dt2 --inserts 1970
You ca choose what range of dates you want to insert - maybe anything before 1970 will become 1970, maybe anything before 1753, maybe only 0001-01-01 .. you choose in the "case when" logic
This is yet another reason why you should prefer DateTime2 over DateTime - The DateTime2 data type supports the same date range as the .Net framework's DateTime struct - from January 1st 0001 to December 31 9999.
Change the MyDateTime data type to DateTime2, and the default value to 0001-01-01:
ALTER TABLE MyTable
ALTER COLUMN MyDateTime DateTime2 NOT NULL
To change the default value constraint you need drop it and re-create it.
This can be easily done using SSMS (just find it, right-click and drop) but using T-SQL you will have use one of the answers from this post since you didn't specify it's name. Once you've done that, you can add it (with a proper name this time):
ALTER TABLE MyTable
ADD CONSTRAINT DF_MyDateTime DEFAULT ('0001-01-01') FOR MyDateTime
I am trying to update a datetime column in a SQL Server 2012 table by using
newItem.DateSaved = DateTime.Today;
I want to save only the Date part of DateTime, but when I am checking in the table I can see that it saves also the time part: 2018-07-27 00:00:00.000 .
How I can make it to store only date part? 2018-07-27 ?
Edit
Because my column is datetime, I see that I can't store only the date part. But how I can show to the user only the date part without time? Here is the select part of the Linq-to-SQL query:
select new { Date = smv.DateSaved.Value.Date }).Distinct();
A datetime column always has a time part - just, in your case it will all be zeros. A datatime is just a number under the hood; it doesn't have any choice about what it has / doesn't have; similarly, it doesn't have any notion of formatting until your code tries to display it, and then it is the dispalying code that chooses the format.
If you don't want a time part, use date instead of datetime for your column.
Change column type in SQL Server from datetime to date (https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql?view=sql-server-2017)
If you want to store only the date without time in SQL Server database you can set the column type to date
ALTER TABLE table_name
ALTER COLUMN DateSaved date;
Reference: https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql?view=sql-server-2017
If you have a DateTime property in your model and you want to show only the date part just format it in your control in the View. For example:
$"{newItem.DateSaved:yyyy-MM-dd}"
or
newItem.DateSaved.ToString("yyyy-MM-dd")
You can also use "d" or "D" (short and long version) instead of specific format like "yyyy-MM-dd" if you want to have default formatting.
If your view is written in HTML or XAML do it there using the same formatting technique.
It is because your field on the database is DateTime. If you want to store just date, you should have a field with date data type. In this link, you can see the difference between the date data types.
In my database I have used Timestamp in each table to see when data was inserted.
It stores data in byte[] of 8 byte.
Now I want to read that time using C#.
How can I get DateTime object from Timestamp which is byte[]?
SQL Server's TIMESTAMP datatype has nothing to do with a date and time!
It's just a binary representation of a consecutive number - it's only good for making sure a row hasn't change since it's been read.
In never versions of SQL Server, it's being called RowVersion - since that's really what it is. See the MSDN docs on ROWVERSION:
Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism
for version-stamping table rows. The
rowversion data type is just an incrementing number and does not
preserve a date or a time. To record a date or time, use a datetime2
data type.
So you cannot convert a SQL Server TIMESTAMP to a date/time - it's just not a date/time.
But if you're saying timestamp but really you mean a DATETIME column - then you can use any of those valid date formats described in the CAST and CONVERT topic in the MSDN help. Those are defined and supported "out of the box" by SQL Server. Anything else is not supported, e.g. you have to do a lot of manual casting and concatenating (not recommended).
The format you're looking for looks a bit like the ODBC canonical (style = 121):
DECLARE #today DATETIME = SYSDATETIME()
SELECT CONVERT(VARCHAR(50), #today, 121)
gives:
2011-11-14 10:29:00.470
SQL Server 2012 will finally have a FORMAT function to do custom formatting......
I'm trying to take a 'calendar.selecteddate' from a web form calendar, and pass that date to my sql database date data-type column.
If I select the 5th of January 2014 the entry works fine (2014/05/01). If I select 13th January there is an exception while sending the data to the database. It's converting the date to a yyyy/mm/dd format. Is there a way to change either my sql database data type format - or, a nice bit of code that'll convert it before I pass it to the database?
SqlHandler.SqlQuery(String.Format("INSERT INTO Sessions VALUES ('{0}', '0')"
, Calendar.SelectedDate.ToString()));
thanks as always
Here I am using C# and SQL Server 2005. And my problem is, I have table in SQL Server like this
Status ID CreationDate AccNo Amount
1 1001 5/27/2011 7:56:16 PM 100001 686700
1 1002 5/27/2011 7:56:16 PM 10009 40000
when I am retrieving data like select * from tablename, then the date column will be displayed like below
Status ID CreationDate AccNo Amount
1 1001 2011-05-27 19:56:16.110 100001 686700
1 1002 2011-05-27 20:04:20.470 10009 40000
why it is changing like that and, how to change the date format 2011-05-27 19:56:16.110 to 5/27/2011 7:56:16 PM ?
Thanks,
Anuradha J
A datetime column just stores a date and time value. It doesn't apply, nor store, any formatting information.
If you need these datetimes in a particular format for presentation, then you either need to specify that format during SELECT (by using CONVERT with an appropriate format specifier), or better, leave it up to whatever is consuming the results to perform conversion and formatting.
Looking at the format specifiers available for CONVERT, I can't actually see one that allows mm/dd/yyyy hh:mm:ss, so you'd need to perform two conversions, separately, for the date and time components, or as I say, leave it up to your C# code to perform the formatting. Ugly SQL way:
SELECT
Status,
ID,
CONVERT(varchar(16),CreationDate,101) + ' ' +
CONVERT(varchar(16),CreationDate,8) as CreationDate,
AccNo,
Amount
FROM
tablename
answer dont change it the databse, change how you use the data from the database. in your code.
store the retrieved result in a date time object, then you can do anything you want with it.
the data is the same.
or write a stored proc that changes the output to what ever you want.
look up time handeling in TSQL.
In the code behind you can do the following. Bring the date without converting it into string.
DateTime dt;
string Temp1 = "Your Date from database";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}