Friday, April 8, 2011

How to enforce minimum width of formatted string in C#

I have the following statement

DateTime now = DateTime.Now;
string test = string.Format("{0}{1}{2}{3}", now.Day, now.Month, now.Year, now.Hour);

This gives me:

test = "242200915"

But I'd like to have something like:

test = "2402200915"

So the question is, how can I enforce the string formatter to output each int with the width of 2 while padding with zeroes?

From stackoverflow
  • DateTime now = DateTime.Now;
    string test = now.ToString("ddMMyyyyHH");
    
    SDD : that worked - thx!
  • Why not just do

    String test = DateTime.Now.ToString("ddMMyyyyHH");
    

    You can format the numbers to be a certain width but this seems like more of what you want.

    Joel Coehoorn : Probably because it's exactly the same thing someone else posted 3 minutes earlier. But that's just a guess.
    Nick Berardi : I actually modified it to clarify, it was actually posted at the exact same time.
  • You can use string.Format("{0:000} {0:D3}", 7)
    to get 007 007

    here is a handy overview

    Binary Worrier : You got in just before me, deleting my answer (p.s. I didn't know about 0:D3, nice one)
    sixlettervariables : +1 Composite formatting

0 comments:

Post a Comment