How to ensure 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 would like to have something like:

test = "2402200915"

So the question is, how can I use a string formatter to output each int with a width of 2 when padding with zeros?

+3
source share
3 answers

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

And here's a helpful MSDN review: Custom Number Format Strings

+15
source
DateTime now = DateTime.Now;
string test = now.ToString("ddMMyyyyHH");
+18
source

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

, , .

+1

Source: https://habr.com/ru/post/1703737/


All Articles