Question

I'm making a website using ASP.net Webpage's in WebMatrix 3. I have a database (SQL Server) with a table that contains a record of events. A InDate Column, type Date, is the primary key. However inputted data is rendered as "4/5/2014 12:00:00 AM".

Is this normal? And if it is, how do you remove the time from the date? I have tried looking up a lot of different resources. But found nothing that helped my situation.

If there is any pointers,tips,suggestions or if you need more info. Please let me know.

Thanks'

Update Here is the cshtml file as requested.

@{
   Layout = "~/Layouts/_Site.cshtml";
   PageData.Add("Title","Overview");
   var talkDB = Database.Open("Events");
   string incomingQuery = string.Format("SELECT InDate,Event FROM IncomingEvents WHERE InDate >= GETDATE() AND InDate <= DATEADD(week, 5, GETDATE())");

}


<div id="upcomingEvents" class="alertBox">
    <div id="IncomingEvents">
        <h3>Incoming Events</h3>
        <table class="alertBox">
            @foreach(var row in talkDB.Query(incomingQuery))
            {
                <tr>
                    <td>
                        @row.InDate
                    </td>
                    <td>@row.Event</td>
                    <td>edit</td>
                </tr>
            }
        </table>
    </div>
</div>
Was it helpful?

Solution

The reason it is displayed with a time in your web page is because there is no Date type in .NET - only DateTime and other similar types. When you get a Date type from SQL Server, .NET casts it implicitly as a DateTime. Since there is no time specified in the Date that came from SQL Server, the 0-value is used, which is 12:00:00AM.

In order to display just the date on your web page, you need to write your front-end code to do so.

This can be done by a call to .ToString() on the date property of your data model objects, with the appropriate format string passed in.

See this link for all of the arguments to DateTime.ToString() and what they do: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx

You most likely want something like this:

@row.InDate.ToString("M/d/yyyy");

Which has a short-hand function:

@row.InDate.ToShortDateString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top