Convert DateTime to string with format YYYYMMDD
I have birth dates stored as datetime in SQL Server 2008 like so:
2010-04-25 00:00:00.000
What is the best way, using C#, to convert and format this into a st开发者_C百科ring with a YYYYMMDD
format?
In the end, all I need is a string like:
20100425
Any help is greatly appreciated!
date.ToString("yyyyMMdd");
Should be what you need.
You need to get that value into a DateTime object and then you can use it's ToString() function like so:
.ToString("yyyyMMdd");
Are you able to get the data out of the database as a DateTime (.NET) object? If so, you can use the DateTime's instancename.ToString("yyyyMMdd")
If you haven't gotten to that stage yet, there's quite a few different ways to get the data out. It's a whole Google search in itself...
You just format the date using a custom format string:
string formatted = theDate.ToString("yyyyMMdd");
Note that the date doens't have a format at all when it's stored as a datetime in the database. It's just a point in time, it doesn't have a specific text representation until it's specifically created from the date.
Use the .ToString() method on the date time object, and pass in the format you want.
精彩评论