Saving C# dates in SQL Server is very common. But if the date formats used in Application and SQL Server are different, it's a nightmare to handle it. Specially when consider future changes in format/regional settings/locale etc.
This simple trick in data saving will make sure dates will save without any problem even date formats are changed in Windows or SQL Server.
The trick:
1. Convert the C# date.ToString("")
2. Use SQL Convert(datetime,, )
3. Match the formatting used in and
E.g.
DateTime dob = new DateTime(1980, 12, 31, 23, 59, 59);StringBuilder buffer = new StringBuilder();
buffer.Append("INSERT INTO [dbo].[Employees] ");
buffer.Append("(EmployeeID,EmployeeName,DateOfBirth,IsActive) ");
buffer.Append("VALUES ");
buffer.AppendFormat("(1,'Name',CONVERT(datetime, '{0}', 126), 1)", dob.ToString("yyyy-MM-ddThh:mm:ss.FFF"));
string sql = buffer.ToString();//Working SQL
**** Here SQL Format Number=126 is actually yyyy-MM-ddThh:mm:ss.FFF format
References:
1. SQL Server Date Format Numbers
2. C# Date Formatting
This simple trick in data saving will make sure dates will save without any problem even date formats are changed in Windows or SQL Server.
The trick:
1. Convert the C# date.ToString("
2. Use SQL Convert(datetime,
3. Match the formatting used in
E.g.
DateTime dob = new DateTime(1980, 12, 31, 23, 59, 59);StringBuilder buffer = new StringBuilder();
buffer.Append("INSERT INTO [dbo].[Employees] ");
buffer.Append("(EmployeeID,EmployeeName,DateOfBirth,IsActive) ");
buffer.Append("VALUES ");
buffer.AppendFormat("(1,'Name',CONVERT(datetime, '{0}', 126), 1)", dob.ToString("yyyy-MM-ddThh:mm:ss.FFF"));
string sql = buffer.ToString();//Working SQL
**** Here SQL Format Number=126 is actually yyyy-MM-ddThh:mm:ss.FFF format
References:
1. SQL Server Date Format Numbers
2. C# Date Formatting