Sunday, August 22, 2010

MVC Html Extension Method to Output a JavaScript Date Object

Here’s a quick MVC HTML extension method that outputs a JS date object.  It’d be nice if JS had a way to represent a date literal outright, but this works just the same.  The tricky part with the Date() constructor is the inconsistent parameters.  Year is the year, Month is the month 0-11, Day is the day of month (1-31), and the times are all zero-based.

Usage:

<script type="text/javascript">
    var d = <%: Html.JSDate(DateTime.Now) %>;
        
    // today is 8/22/2010, here's the output:
    // new Date(2010,7,22,19,7,34,532)
</script>

Source:

/// <summary>
/// Outputs a javascript date object declaration
/// </summary>
public static string JSDate(this HtmlHelper html, DateTime date)
{
    return string.Format("new Date({0},{1},{2},{3},{4},{5},{6})",
        date.Year, date.Month - 1, date.Day, date.Hour, date.Minute, 
            date.Second, date.Millisecond);
}

0 comments:

Post a Comment