Quantcast
Channel: RobVolk.com » ASP.NET MVC
Viewing all articles
Browse latest Browse all 3

MVC Html Extension Method to Output a JavaScript Date Object

$
0
0

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) %>;
</script>

Output

// today is 8/22/2010
var d = new Date(2010,7,22,19,7,34,532)

Source

///
/// Outputs a javascript date object declaration
///
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);
}

The post MVC Html Extension Method to Output a JavaScript Date Object appeared first on RobVolk.com.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images