Converting a string to datetime from “yyyy-MM-dd”

2019-06-18 04:35发布

问题:

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.

回答1:

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);


回答2:

Maybe ParseExact function can help you.

DateTime dResult = DateTime.ParseExact("2012-07-18", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);


回答3:

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 :)



回答4:

in sql server you can use the query
SELECT CONVERT(VARCHAR(10), GETDATE(), 120) AS [YYYY-MM-DD]



回答5:

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);