ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DateTimeFormat

This is extension method for format the data time into the string with pattern specific and current culture. For more information please read at my blog http://weblogs.asp.net/thangchung/archive/2010/11/01/datetime-formating-extension-method.aspx

Source

public static string ToStringFormat(this DateTime source, Expression<Func<DateTimeFormat>> dateTimeFormat)
{
    var dateTimeFormatCompiled = dateTimeFormat.Compile().Invoke();

    var dateTimeStringFormat = StringEnum.GetStringValue(dateTimeFormatCompiled);

    var currentCulture = Thread.CurrentThread.CurrentCulture;

    return source.ToString(dateTimeStringFormat, currentCulture);
}

Example

var shortDateResult = DateTime.Now.ToStringFormat(() => DateTimeFormat.ShortDate);
var fullLongDateTimeResult = DateTime.Now.ToStringFormat(() => DateTimeFormat.FullLongDateTime);
var rfc1123Result = DateTime.Now.ToStringFormat(() => DateTimeFormat.Rfc1123LowerCase);

Author: thangchung

Submitted on: 1 nov. 2010

Language: C#

Type: System.DateTime

Views: 10450