I have the following code -
DateTime timeStamp;
timeStamp = System.Convert.ToDateTime(y.InnerText);
Where y.InnerText
is 11/03/2013 11:35:24
.
However this is breaking my import statement as it the database is looking for the format -
2013-03-11 11:35:24
How can I set the format of the DateTime object?
C# DateTime Format Date and Time in C# are handled by DateTime class in C# that provides properties and methods to format dates in different datetime formats. This article blog explains how to work with date and time format in C#. The following table describes various C# DateTime formats and their results.
uses a default date format to store and manipulate strings that represent dates. To specify the default date format, enter a date format in the DateTime Format String attribute in the data viewer configuration. By default, the date format is MM/DD/YYYY HH24:MI:SS.US.
SQL Server comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: a unique number.
How can I set the format of the DateTime object?
You can't. DateTime
values don't have formats, any more than int
or double
values do. When you want to convert them to/from strings, that's where you specify any formatting information.
Instead, you should use parameterized SQL and avoid converting the DateTime
value back into a string in the first place. This is a general best practice - don't include values in your SQL string; parameterized SQL has multiple benefits:
I would also suggest that instead of using Convert.ToDateTime
, you specify your expected format when parsing. For example:
timeStamp = DateTime.ParseExact(y.InnerText,
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Basically, the two rules I try to apply are:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With