Click here to Skip to main content
15,905,614 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone, I've an entity data model added to my project and I'm populating a number of text-boxes with the datetime value from the EDM.
C#
txtFinancialYearFrom.Text = Convert.ToString(company.FinancialYearFrom);

But I'd like to try to write an extension method that takes that datetime value and reformats it into MMMMd format. Here's what I have so far:
C#
namespace ExtensionLibrary
{
    //Extension methods must be defined in a static class
    public static class DateFormatExtension
    {
        // This is the extension method.
        public static String MMMMdFormat(this DateTime date)
        {
            return new String(date.ToString("d MMMM"));
        }
    }
}

at the minute this is giving me 2 errors:
Error 1 The best overloaded method match for 'string.String(char[])' has some invalid arguments
Error 2 Argument 1: cannot convert from &#39;string&#39; to &#39;char[]&#39;</pre>
Has anyone tried this before?
Posted

All you need to do is remove the "new String" bit:

C#
public static class MyExtensions
    {
    public static String MMMMdFormat(this DateTime date)
        {
        return date.ToString("d MMMM");
        }
    }
 
Share this answer
 
thank you OriginalGriff, here's what I have ended up with:
C#
namespace ExtensionLibrary
{
    //Extension methods must be defined in a static class
    public static class ExtensionLibrary
    {
        //This method handles any NULLABLE Datetime fields
        public static String FormatNULLDateTime(this DateTime? date)
        {
            if (date.HasValue)
                return ((DateTime)date).ToString("dd MMMM");
            else
                return "";
        }

        //This method handles non-NULLABLE Datetime fields
        public static String FormatDatetime(this DateTime date)
        {
            return ((DateTime)date).ToString("dd MMMM");
        }
    }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900