Technodrone

there's some good in this world, Mr. Frodo... and it's worth fighting for.

  Home  |   Contact  |   Syndication    |   Login
  14 Posts | 2 Stories | 37 Comments | 0 Trackbacks

News

Article Categories

Archives

Post Categories

Image Galleries

Code hacks

Face Book Profile

LinkedIn Profile

Recommended Products

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);
posted on Friday, January 02, 2009 12:39 PM

Feedback

# re: PadLeft a Handy Function for the New Year 10/3/2009 9:40 PM John K. Hines
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

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: