Reputation: 2087
Even though it seems like this question has been asked a bunch of times, I can't seem to find an answer that is specific to my question:
I have a variable that is read from an XML file by a C# XML parser. It is a string, and is in the format "yyyy-MM-dd"
. I would like to read this variable into our database using SQL
, but it needs to be in the proper datetime format in order for me to do this. Unfortunately, I can't find any datetime formats for "yyyy-MM-dd"
. Am I missing something?
I would prefer to be able to convert the variable to datetime before I have to open my SQL
connection, if possible.
Upvotes: 14
Views: 73867
Reputation: 11
stringDateFormat = "2015-12-25 00:00:00"
string dt= Convert.ToDateTime(stringDateFormat).ToString("d"); // output -> 2015-12-25
Upvotes: 1
Reputation: 69998
If you are not sure it will work you can use "TryParseExact". If it works "success" will be true. This way you are not risking a parse exception.
DateTime timestamp;
bool success = DateTime.TryParseExact("2015-12-25", "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out timestamp);
Upvotes: 3
Reputation: 6053
in sql server you can use the query
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]
Upvotes: 1
Reputation: 1500785
If you're using LINQ to XML, you can simply cast the element or attribute to DateTime
:
DateTime date = (DateTime) element;
Then you can insert it into your database using parameterized SQL. I would argue against Aaron's suggestion: wherever possible, keep your data in its most natural form, which in vanilla .NET is a DateTime
. The more time you can keep data in a meaningful representation, the better IMO.
If you're not using LINQ to XML, then the solutions from smink and Riera are fine - but I'd strongly encourage you to use LINQ to XML if you possibly can :)
Upvotes: 1
Reputation: 369
Maybe ParseExact function can help you.
DateTime dResult = DateTime.ParseExact("2012-07-18", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 5
Reputation: 97849
I would prefer to be able to convert the variable to datetime before I have to open my SQL connection, if possible.
DateTime result = DateTime.ParseExact("2012-04-05", "yyyy-MM-dd", CultureInfo.InvariantCulture);
Upvotes: 37