formatting using C#
I have a function that returns the month and day. I want that if day/month is less than 10 then it should append 0 before it and should开发者_开发问答 return 01 instead of 1. how can I do this ?
Thanks.
return DateTime.Now.ToString("dd"); //day
return DateTime.Now.ToString("MM"); //month
There are a lot of formatting options for dates and times, including specifying your own. How you'd use them depends a lot on how your code is creating and returning a "month and day."
DateTime dt = new DateTime(2011, 3, 4, 16, 5, 7, 123);
String.Format("{0:MM/dd/yyyy}", dt); // "03/04/2011"
Use a custom format when you turn the number into a string:
string dayFormatted = day.ToString("00");
It's not altogether clear what the exact format you want, but if you want the format to be like this:
dd/mm
where both dd
and mm
is formatted with two digits, then string.Format will do that for you:
string.Format("{0:00}/{1:00}", day, month); // 20/03 for today
Of course, if you really have a DateTime, you can do it directly:
string.Format("{0:dd/MM}", DateTime.Now); // 20/03 for today (*)
- (*) note that when using DateTime formatting, / will be replaced with the cultural character for separating parts of a date, so in some cases it might be a dot, not a slash
精彩评论