Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 934
SDD Avatar asked Nov 28 '22 00:11

SDD


2 Answers

DateTime now = DateTime.Now;
string test = now.ToString("ddMMyyyyHH");
like image 119
LukeH Avatar answered Dec 10 '22 09:12

LukeH


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

like image 33
Henk Holterman Avatar answered Dec 10 '22 07:12

Henk Holterman