tags:

views:

47

answers:

3

Here is an example. I expected 1900/01/02 but got 1900/1/2 instead. If "1" was an int it would work. Why DOESNT this return 2 digits? i understand its a string but isnt the point of :00 to specify the digits? Why is it being ignored?

var date = string.Format("{0:0000}/{1:00}/{2:00}", "1900", "1", "2");
+3  A: 

Because strings cannot be formatted like numbers; you can, however, specify a width of the target string (but they get padded with spaces, not 0).

var date = string.Format("{0,4}/{1,2}/{2,2}", "1900", "1", "2");
Lucero
So to get it padded with zeros, you can replace space with 0: `var date = string.Format("{0,4}/{1,2}/{2,2}", "1900", "1", "2").Replace(" ", "0");`
awe
@awe, not really - this will also replace spaces which weren't padding. But one could write a custom formatter for string which does proper padding with a user-defined char if really necessary.
Lucero
For this particular format string, there are no spaces other than those of the padding. I agree it will not work if you include more than just the date in the format string. Like if you say `string.Format("The date is {0,4}/{1,2}/{2,2}", "1900", "1", "2")`, it will not work with a replace, but I don't think that is the issue here.
awe
+3  A: 

Why are you trying to format a date from 3 strings, instead of using a DateTime variable?

Then you could format it easily:

DateTime dt = ...;
var dateString = dt.ToString("yyyy/MM/dd");
// yyyy = 4-digit year, MM = 2 digit month, dd = 2 digit day (with leading 0's)
Hans Kesting
A: 

You need to convert to integer before it can be formatted as number:

var date = string.Format("{0:0000}/{1:00}/{2:00}", int.Parse("1900"), int.Parse("1"), int.Parse("2"));
awe
Or just replace the string literals (`"1900"`) with int literals (`1900`)
Ron Klein
**@Ron:** Yes obviously, but this might just have been an example of a principal, and that the real world code used string variables ( otherwise he could just say `var date = "1900/01/02";` !)
awe
@awe: Yes, I see your point.
Ron Klein