Thursday, October 25, 2012

Day/Month DateTime extension method

Here's a simple extension method for DateTime that displays a date time in the culture-specific format for Day/Month:

public static class DateTimeExtension{
    public static string ToDayMonthString(this DateTime dt, CultureInfo culture){
        var dateString = dt.Date.ToString("d", culture);
        var year = dt.Year.ToString( CultureInfo.InvariantCulture );
        var dateSeparator = culture.DateTimeFormat.DateSeparator;
        var dayMonth = dateString.IndexOf(year, StringComparison.Ordinal) == 0
                       ? dateString.Replace(year + dateSeparator, string.Empty)
                       : dateString.Replace(dateSeparator + year, string.Empty);
        return dayMonth;

Hope you find this useful.

No comments:

Post a Comment