Artem Community
Artem interactive communities
DateTime.ToSiteString() Extension Method

I'm mostly using LINQ to SQL and Entity Framework recently.
As you know, the datetime database fields are returned as Nullables of type DateTime, if they allow NULL values and I found myself adding a lot of additional data class properties like:

public string ModifiedString {

    get {

        return this.ModifiedOn.HasValue

            ? this.ModifiedOn.Value.ToString("dd MMM yyyy") : "";

    }

}

So, I decided to wrap that an a nice Extension Method, make it once, and then just use it.

And here is what I came up with:

namespace System {

 

    /// <summary>

    ///

    /// </summary>

    public static class XtsDate {

 

        #region Static Fields /////////////////////////////////////////////////////////////////////

 

        /// <summary>

        /// Gets the date format.

        /// </summary>

        /// <value>The date format.</value>

        public static string DateFormat = "dd MMM yyyy";

 

        #endregion

 

        #region Static Methods ////////////////////////////////////////////////////////////////////

 

        /// <summary>

        /// Toes the site string.

        /// </summary>

        /// <param name="date">The date.</param>

        /// <returns></returns>

        public static string ToSiteString(this DateTime date) {

            return date.ToString(DateFormat);

        }

 

        /// <summary>

        /// Toes the site string.

        /// </summary>

        /// <param name="date">The date.</param>

        /// <returns></returns>

        public static string ToSiteString(this DateTime? date) {

            return date.HasValue ? date.Value.ToString(DateFormat) : "";

        }

        #endregion

    }

}

Now, when I need some DateTime field as string I just can use:

return this.ModifiedOn.ToSiteString();

 

Hope this helps anyone ...

Regards


Posted 01-12-2009 14:12 by velio
Filed under:
Powered by Community Server (Non-Commercial Edition), by Telligent Systems