none
How to format string in C#? RRS feed

  • Question

  •  

    Hi,

     

    How do I format a date in C#? In my application a date is represented as "2008-03-11 00:00:00" This causes some problems as I need the format to be "2008-03-11".

     

    BirthDate is a value retrieved from an Access database,like so:

     

    string strDate = reader["BirthDate"].ToString(); 

     

    The format is 2008-03-11 00:00:00. How do I format this value?

     

     

    I appreciate any help!

    Tuesday, March 11, 2008 9:30 AM

Answers

  •  

    incase the field is DateTime

     

    string strDate = ((DateTime)reader["BirthDate"] )ToString("yyyy-mm-dd"); 
    Tuesday, March 11, 2008 1:30 PM

All replies

  • Hi,

    Take a look to this:

    http://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspx
    Tuesday, March 11, 2008 9:46 AM
  •  

    incase the field is DateTime

     

    string strDate = ((DateTime)reader["BirthDate"] )ToString("yyyy-mm-dd"); 
    Tuesday, March 11, 2008 1:30 PM
  • Thanks Zaben!

     

    Very interesting solution. One problem though, when I type 1980-07-16 using your formatting method I get the result 1980-00-16. This happens every time. If I change the format to yyyy-dd-mm I get 1980-16-00. Strange!

     

    Your formatting again

     

    string strDate = ((DateTime)reader["BirthDate"] )ToString("yyyy-mm-dd"); 

     

     

    Thanks again!

     

    Tuesday, March 11, 2008 3:15 PM
  • TRY THIS  "yyyy-MM-dd"

     

    Lower cas M's are for minutes

    Upper case M's are for months

     

    ( I remember this because months are bigger than minutes)

    Tuesday, March 11, 2008 5:22 PM
  •  

    Yes as Tom Said capital MM for month and not small mm because small mm for minutes.

     

    http://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspx

     

     

    string strDate = ((DateTime)reader["BirthDate"] )ToString("yyyy-MM-dd"); 

     

     

    Thanks

    Tuesday, March 11, 2008 8:51 PM