format string from 8 to 08 for August.

  • Thread starter Thread starter moondaddy
  • Start date Start date
M

moondaddy

I need to format a string to it always has 2 digits in it. I'm getting the
month like this:

DateTime.Now.Month.ToString()

Right now since it's August, this returns a string of "8", however, I need
to return a string of "08". Is there a format method what will
automatically pad this for me?

Thanks.
 
I need to format a string to it always has 2 digits in it.  I'm gettingthe
month like this:

DateTime.Now.Month.ToString()

Right now since it's August, this returns a string of "8", however, I need
to return a string of "08".  Is there a format method what will
automatically pad this for me?

Thanks.


use DateTime.Now.ToString("MM");

take a look at the different DateTime format strnig options
 
But the .ToString seems both more readable and more
flexible.

Arne

You can do it either way, it formats the string the way your format
string specifies.

Read up on string formatting. It's very interesting. Try experimenting
with string formatting by using the string.Format() function. There
are lists of format codes on the web, just google for format string C#.
 
moondaddy said:
I need to format a string to it always has 2 digits in it. I'm getting the
month like this:

DateTime.Now.Month.ToString()

Right now since it's August, this returns a string of "8", however, I need
to return a string of "08". Is there a format method what will
automatically pad this for me?

Thanks.

Here are some ways of doing it (including the ones already mentioned in
the thread):

DateTime.Now.Month.ToString("00")
DateTime.Now.Month.ToString("D2")
DateTime.Now.ToString("MM")
string.Format("{0:00}", DateTime.Now.Month)
string.Format("{0:D2}", DateTime.Now.Month)
string.Format("{0:MM}", DateTime.Now)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top