tags:

views:

492

answers:

5

I know I can use substring or other methods, but I'm just curious if there is something to replace the ? below to have it return "09"

String.Format({0:?}, 2009);

btw, I came across a good cheat sheet while trying to figure this out... http://john-sheehan.com/blog/wp-content/uploads/msnet-formatting-strings.pdf

+2  A: 
(2009 % 100).ToString("00");
Joel Coehoorn
Nope, that just shows the full "2009"
bdukes
Should be better now.
Joel Coehoorn
+1  A: 

I'm 99.9% certain this cannot be done unless you have the year stored in a DateTime...

John Rasch
+3  A: 

I really think that you ought to do this:

String s = "2009";
s.Substring(s.Length - 2);

There is no way to format that string to restrict the number of digits like you want to.

Andrew Hare
+1 I was just about to post that exact code snippet
Fredrik Mörk
+4  A: 

I saw the question, and at the risk of being flamed, I want to point this out:

If you're formatting a DateTime, or you've got a Date you're formatting you can simply do a ToString("yy"). Likewise if you're only dealing with years.

DateTime dt = new DateTime(2009, 1, 1); //any DateTime would do, really.
return dt.ToString("yy"); //"09"

but if this is some weird generic I want the last two characters of a string business, the fastest route is:

string numString = someInt.ToString();
return numString.Substring(numString.Length - 2);
blesh
I won't flame you, but these are the obvious alternative methods I wasn't looking for, I was just trying to learn more about number formatting.
jayrdub
+4  A: 

If you have a legitimate need for something more sophisticated, you can always create your own custom format provider: http://msdn.microsoft.com/en-us/library/system.iformatprovider.aspx

You can then format your strings in whatever pattern you want, and properly encapsulate the functionality for reuse.

Here is an example:

class Program
{
    static void Main(string[] args)
    {
        var date = "2009";

        Console.Write(string.Format(new CustomFormatProvider(), "{0:YY}", date));

        Console.ReadKey();
    }

    public class CustomFormatProvider : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type formatType)
        {
            if (formatType == typeof(ICustomFormatter))
                return this;
            else
                return null;
        }

        public string Format(string fmt, object arg, IFormatProvider formatProvider)
        {
            string year = arg.ToString();
            string result = string.Empty;
            fmt = fmt.Trim().ToUpper();

            if (fmt.Equals("YY")) 
                return year.Substring(2, 2);
            else if (fmt.Equals("YYYY"))
                return year;
            else 
                throw new FormatException(String.Format("{0} is not a valid format string.", fmt));

        }
    }
}
chrisghardwick