SDD
SDD

Reputation: 1451

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?

Upvotes: 5

Views: 5612

Answers (3)

Henk Holterman
Henk Holterman

Reputation: 273244

You can use string.Format("{0:000} {0:D3}", 7)
to get 007 007

And here is a useful overview on MSDN: Custom Numeric Format Strings

Upvotes: 17

Nick Berardi
Nick Berardi

Reputation: 54854

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.

Upvotes: 2

LukeH
LukeH

Reputation: 269368

DateTime now = DateTime.Now;
string test = now.ToString("ddMMyyyyHH");

Upvotes: 20

Related Questions