Tutorial :Convert DateTime to string with format YYYYMMDD



Question:

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 string with a YYYYMMDD format?

In the end, all I need is a string like:

20100425  

Any help is greatly appreciated!


Solution:1

date.ToString("yyyyMMdd");  

Should be what you need.


Solution:2

You need to get that value into a DateTime object and then you can use it's ToString() function like so:

.ToString("yyyyMMdd");  


Solution:3

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...


Solution:4

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.


Solution:5

Use the .ToString() method on the date time object, and pass in the format you want.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »