PadLeft a Handy Function for the New Year

I came into the office on January 2, 2009 and found out one of my applications was not finding files that have names based on the day of year and month of year.  Here is the problem, my code was looking for a file called  'thepreciousfile200911.txt" instead of "thepreciousfile200901001.  This worked 12/28/2008 but when the day of year changed to a single digit on the new year I could no longer check for file existence because the string I was using for the file name was now wrong. When I retrieved the day of year from the current month I blanked out and did not think it would return as 1 and if it did that was the correct file name anyway. Well it was wrong.  Here is what I did to fix it and it was extremely easy.

 

In this example the 3 is the number of characters I want the resulting string to have and the '0' is the character you want to use for padding if the day of year does not equal 3 characters. 

string dayofyear = Convert.ToString(DateTime.Now.DayOfYear).PadLeft(3, 0);
  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
posted @ Friday, January 02, 2009 12:39 PM
Print

Comments on this entry:

# re: PadLeft a Handy Function for the New Year

Left by John K. Hines at 10/3/2009 9:40 PM
Gravatar
You can also use:
string dayofyear = DateTime.Now.DayOfYear.ToString("D3")

Format codes are cryptic but occasionally handy.
http://blogs.msdn.com/kathykam/archive/2006/03/29/564426.aspx

Your comment:



(not displayed)


 
 
 
 
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910