views:

122

answers:

1

I tried to create a view helper which takes a DateTime object and returns a string. If the DateTime object equals a new DateTime(0), the function returns an empty string. Otherwise return a formatted DateTime string. This works so far.

public static string DateTimeOrEmpty(this HtmlHelper htmlHelper, DateTime dateTime)
{
    return dateTime.ToString().Equals(new DateTime(0).ToString()) 
        ? String.Empty 
        : dateTime.ToString("{0:g}");
}

The Problem is, that I'd like to pass the format ("{0:g}") as a parameter:

public static string DateTimeOrEmpty(this HtmlHelper htmlHelper, DateTime dateTime, string format)
{
    return dateTime.ToString().Equals(new DateTime(0).ToString()) 
        ? String.Empty 
        : dateTime.ToString(format);
}

But it doesn't work properly. If I call the helper from my view

<%: Html.DateTimeOrEmpty(Model.StopDate, "{0:g}") %>

the function with "{0:g}" as parameter for "format", I get something like "{O:n. Chr.}", which is not what I expect

+2  A: 

The {0:} part is for formatting string.Format parameters - you just want the "g" to pass into ToString().

<%: Html.DateTimeOrEmpty(Model.StopDate, "g") %>

However, I'd recommend you

  1. do the comparisons on the raw DateTime values - or if you do want to compare strings you only construct the display string once and re-use that
  2. you use the static DateTime.MinValue for the comparison rather than creating a new DateTime each time - or at least create one static instance to compare against.

i.e.

public static string DateTimeOrEmpty(this HtmlHelper htmlHelper, DateTime dateTime, string format)
{
    return (dateTime == DateTime.MinValue)
        ? String.Empty 
        : dateTime.ToString(format);
}
Rup
Great!! It works. Thank you for your solution and the DateTime.MinValue hint. It has better performance and is easyier to read :)
Werner Heisenberg
I'd also suggest using a nullable DateTime ( DateTime? ) instead of DateTime.MinValue.
dave thieben
I did already overload the method for a DateTime? parameter.
Werner Heisenberg