locked
Gridview showing Date value as DateTime 2/2/2020 12:00:00AM RRS feed

  • Question

  • User2142845853 posted

    This is a VB.net app in asp.net web forms.  The goal is to display the column of the date as just a date mm/dd/YYYY.   The data comes from a SQL table, passed into the model as a date, where it instantly appends the time.  Even though the variable is a type Date.  Seems like its not possible to remove the time from the gridview1 control?

    model:

    <Column("Date of selection")>
    Public Property Dateofreport As Date

    con.Open()
     Dim rdr As SqlDataReader = cmd.ExecuteReader()
     ' READ THE FILE AND FILL THE LIST
         While rdr.Read()
            Dim ASTR As ASTR = New ASTR ()
                    ASTR.Id = Convert.ToInt32(rdr("Id"))
                    ddatte = rdr("Date of report")    
                    duodate = (ddatte.Month.ToString() + "/" + ddatte.Day.ToString() + "/" + ddatte.Year.ToString())  
                    ASTR.Dateofreport = duodate   <- 2/1/2020 goes in
    
    

    read from the SQL table, at the last line it switches from the date to appending the time of 12:00:00am.  In debug ASTR.Dateofreport becomes 2/1/2020 12:00:00 AM even though its type Date not DateTime.  List built, then 

    Gridview1.DataBind() and its in there.  In the Grid theyre all template fields and have DataFormatString="{0:d}" for the ITEM template field on the date column, shows time still how to cover up the times?

    Sunday, February 2, 2020 8:41 AM

All replies

  • User409696431 posted

    Use date formatting:

    <asp:BoundField DataField="Dateofreport" HtmlEncode="false" DataFormatString="{0:mm/dd/yyyy}" />

    As to why SQL server adds the time: is the type DATE or DATETIME in the database?  If the column in the database is DATETIME, it will add the default time. That is what matters.

    Sunday, February 2, 2020 10:08 AM
  • User2142845853 posted

    well I broke visual studio.  again.   Its not failing to compile because of HTML code... the change from DataFormatString being 0:d  to 0:mm/dd/yyyy  now it crashes, in the .aspx file saying value cannot be null.  

    when does it ever break on error in the HTML file?   and with no error in the html

    Sunday, February 2, 2020 3:14 PM
  • User475983607 posted

    when does it ever break on error in the HTML file?   and with no error in the html

    The HTML does not know you are passing it a null value.  Share you code if you need the community to review your code for correctness.

    Sunday, February 2, 2020 3:53 PM
  • User2142845853 posted

    Thats what I mean, Ive never seen VS break on the html code.  Click DEBUG/GO it compiles, then lands on the aspx page pointing to the wrong thing

    </FooterTemplate>
         <ItemTemplate>
            <asp:Label ID="Label3" runat="server" DataFormatString="{0:mm/dd/YYYY}" Text='<%# Bind("Dateofreport.") %>'></asp:Label>
         </ItemTemplate>

    The line asp:Label  is highlighted with the VS error message.  

    Return the line how it was when it ran.  No difference.  close solution/restart, it says VS updated and these files were recovered:  (the files Im using) recover, now it throws the error on a BLANK page.  its pulling up a different file the .aspx.vb with code on it,  but the file is empty.  open file location, says the file is 40kb.  but it wont show it.  Stop debugging and it says file name.aspx cant be found!  restart again, same blank empty files. 

    This is typical, I dont expect VS to run properly.  it complains with int x = 1;  x is not defined.  Got close to the answer, but the VS shut down all file modifications, a conspiracy.  The government is lying.  but we uncover the truth.  This is truthisodes... 

    Sunday, February 2, 2020 4:24 PM
  • User2142845853 posted

    It complains that PropName cannot be null.  This is something in javascript.  Nothing I use or touched is called PropName.  shows the wrong page still after rebooting but detail shows why it complains.  Visual Studio messed up the project.  

    removeAttr: function( elem, value ) {
    		var name, propName,
    			i = 0,
    			attrNames = value && value.match( core_rnotwhite );
    
    		if ( attrNames && elem.nodeType === 1 ) {
    			while ( (name = attrNames[i++]) ) {
    				propName = jQuery.propFix[ name ] || name;
    
    				// Boolean attributes get special treatment (#10870)
    				if ( jQuery.expr.match.bool.test( name ) ) {
    					// Set corresponding property to false
    					if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
    						elem[ propName ] = false;
    					// Support: IE<9
    					// Also clear defaultChecked/defaultSelected (if appropriate)
    					} else {
    						elem[ jQuery.camelCase( "default-" + name ) ] =
    							elem[ propName ] = false;
    					}
    
    				// See #9699 for explanation of this approach (setting first, then removal)
    				} else {

    Sunday, February 2, 2020 6:15 PM
  • User475983607 posted

    The syntax is incorrect for a template field, the format string is incorrect, and it looks like you have a typo where Dateofreport ends with a dot.

    <ItemTemplate>
       <asp:Label ID="Label3" runat="server" DataFormatString="{0:mm/dd/YYYY}" Text='<%# Bind("Dateofreport.") %>'></asp:Label>
    </ItemTemplate>

    Below you'll find a working example based on the official GridView date format docs.

        <asp:GridView ID="StudentGrid" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="First Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("FirstName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("FirstName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                    <EditItemTemplate>
                        <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("LastName") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Bind("LastName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Enrollment Date">
                    <EditItemTemplate>
                        <asp:TextBox ID="EnrollmentDate" runat="server" Text='<%# Bind("EnrollmentDate") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="EnrollmentDate" runat="server" Text='<%# Bind("EnrollmentDate", "{0:MM/dd/yyyy}") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                PopulateStudentGrid()
            End If
        End Sub
    
        Protected Sub PopulateStudentGrid()
    
            'Turn on the Dbcontext
            Dim Db As New ContosoModel()
    
            'Query the database
            Dim results As New List(Of Student)
            results = Db.Students.ToList()
    
            'Bind the query results to the GridView
            StudentGrid.DataSource = results
            StudentGrid.DataBind()
    
        End Sub
    <Table("Student")>
    Partial Public Class Student
        Public Sub New()
            Enrollments = New HashSet(Of Enrollment)()
        End Sub
    
        Public Property StudentID As Integer
    
        <StringLength(50)>
        Public Property LastName As String
    
        <StringLength(50)>
        Public Property FirstName As String
    
        Public Property EnrollmentDate As Date?
    
        Public Overridable Property Enrollments As ICollection(Of Enrollment)
    End Class

    Sunday, February 2, 2020 7:01 PM
  • User475983607 posted

    It complains that PropName cannot be null.  This is something in javascript.  Nothing I use or touched is called PropName.  shows the wrong page still after rebooting but detail shows why it complains.  Visual Studio messed up the project.  

    removeAttr: function( elem, value ) {
    		var name, propName,
    			i = 0,
    			attrNames = value && value.match( core_rnotwhite );
    
    		if ( attrNames && elem.nodeType === 1 ) {
    			while ( (name = attrNames[i++]) ) {
    				propName = jQuery.propFix[ name ] || name;
    
    				// Boolean attributes get special treatment (#10870)
    				if ( jQuery.expr.match.bool.test( name ) ) {
    					// Set corresponding property to false
    					if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
    						elem[ propName ] = false;
    					// Support: IE<9
    					// Also clear defaultChecked/defaultSelected (if appropriate)
    					} else {
    						elem[ jQuery.camelCase( "default-" + name ) ] =
    							elem[ propName ] = false;
    					}
    
    				// See #9699 for explanation of this approach (setting first, then removal)
    				} else {

    It is difficult to comment on the incomplete JavaScript function.   It looks like the function is dependent on a naming convention to find attribute name.   I can only assume you did not follow the naming convention and why you are receiving a null reference.  Use the browser's dev tool to set a break point and single step through the code or share all the relevant code and how the function is called if you need community support.

    Sunday, February 2, 2020 7:11 PM
  • User2142845853 posted

    Yes had the period on Dateofreport hoping it had options, thought it being a string wouldnt throw an exception but took out the DataFormatString and it runs.

    Now back to the first problem, a LIST is built reading the table, the TYPE of the date item is just DATE. Its not DateTime.  Once the rdr is going thru all records, the date goes to a variable, then to FORCE the issue, the string is built using  variable.Month + "/" + variable.Day + "/" + variable.Year and its perfect, 02/01/2020  with no time in there.  Once the model based List item has the date added, it appends the time while the variable that fed it is still date only. 

    why does a type DATE when given just the DATE part without time, append the TIME?  Id only expect this from a DATETIME type.  is this yet another bug in the VS?

    dim var1 as Date

    var1 = 2/2/2020

    print var1  ==>  2/2/2020 12:00:00

    Sunday, February 2, 2020 7:33 PM
  • User475983607 posted

    rogersbr

    why does a type DATE when given just the DATE part without time, append the TIME?  Id only expect this from a DATETIME type.  is this yet another bug in the VS?

    No this is a bug in your understanding.  Please read the official docs; https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/date-data-type

    Your sample code does not compile which makes the intend a bit fuzzy.  

    dim var1 as Date
    
    var1 = 2/2/2020
    
    print var1  ==>  2/2/2020 12:00:00

    A working example.

        Sub Main()
            Dim var1 As Date = New Date(2020, 2, 2)
            Console.WriteLine(var1.ToString())
            Console.WriteLine(var1.ToShortDateString())
            Console.WriteLine(var1.ToString("MM/dd/yyyy"))
        End Sub
    2/2/2020 12:00:00 AM
    2/2/2020
    02/02/2020

    I think you'll be interested in reading about the standard and custom date format strings in .NET.

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

    https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

    Sunday, February 2, 2020 8:22 PM
  • User2142845853 posted

    thanks for the reference links.  Nothing in these links works to force the DATE or DATETIME variable into a Shortdate, it will not accept formatting of the #02/02/2020#  it expands it out with the time.  None of the Microsoft commands will make that value the date only

    Sunday, February 2, 2020 9:57 PM
  • User475983607 posted

    thanks for the reference links.  Nothing in these links works to force the DATE or DATETIME variable into a Shortdate, it will not accept formatting of the #02/02/2020#  it expands it out with the time.  None of the Microsoft commands will make that value the date only

    No, the documentation is correct. 

    Holds IEEE 64-bit (8-byte) values that represent dates ranging from January 1 of the year 0001 through December 31 of the year 9999, and times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM. Each increment represents 100 nanoseconds of elapsed time since the beginning of January 1 of the year 1 in the Gregorian calendar. The maximum value represents 100 nanoseconds before the beginning of January 1 of the year 10000.

    https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/data-types/date-data-type

    It seems you think assigning a short date to a Date or DateTime type will magically affect the Date format.  It does not. 

        Sub Main()
            Dim var1 As Date = #02/02/2020#
            Console.WriteLine(var1.ToString())
            Console.WriteLine(var1.ToShortDateString())
            Console.WriteLine(var1.ToString("MM/dd/yyyy"))
        End Sub
    2/2/2020 12:00:00 AM
    2/2/2020
    02/02/2020

    Monday, February 3, 2020 1:26 AM
  • User2142845853 posted

    You still didnt address the question.  No formatting in all types listed, none cause the Date to show just the Date in the gridview in the mentioned variable. 

    Monday, February 3, 2020 2:49 AM
  • User-719153870 posted

    Hi rogersbr,

    As far as i know, the format will be converted to datetime not matter it was Date or Datetime in your database.

    You can think this as a default behavior rather than a Bug of VS.

    Best Regard,

    Yang Shen

    Monday, February 3, 2020 5:02 AM
  • User475983607 posted

    You still didnt address the question.  No formatting in all types listed, none cause the Date to show just the Date in the gridview in the mentioned variable. 

    That's not true.  I provided a working GridView example with source code.   I also proved several more formatting examples, reference to the data format documentation, and a reference to the vb.net Date type.

    The problem you are facing is your expectation does not match how the framework libraries actually work.

    Monday, February 3, 2020 12:46 PM
  • User2142845853 posted

    What I said is completely true.  You simply argue and cause problems, just to be unprofessional.

    Monday, February 3, 2020 6:34 PM
  • User2142845853 posted

    Hi Yang Shen

    thanks, after review I remembered how the type Date would take both and DateTime was an improved version;  But the gridview has the date + unwanted time text

    Monday, February 3, 2020 6:37 PM
  • User475983607 posted

    What I said is completely true.  You simply argue and cause problems, just to be unprofessional.

    Come on now you know it's not true. 

    If you are still seeing the date and time in the browser after making the format change, then you are doing something wrong.  Share all the relevant code so the community can help fix the bugs.

    Monday, February 3, 2020 7:00 PM
  • User2142845853 posted

    this is about the gridview showing the date and 12:00:00 instead of just the date.  build a list of type DATE and send that into the gridview.  displaying the date alone in the gridview is the problem.

    make a model with type DATE, feed the list and bind to the gridview, which has the template fields.  do some magic such that it accepts the datetime and only displays the date.  it always displays the uninitialized time like from the VCR era  12:00  (blinks on/off)

    Tuesday, February 4, 2020 4:35 AM
  • User475983607 posted

    rogersbr

    this is about the gridview showing the date and 12:00:00 instead of just the date.  build a list of type DATE and send that into the gridview.  displaying the date alone in the gridview is the problem.

    make a model with type DATE, feed the list and bind to the gridview, which has the template fields.  do some magic such that it accepts the datetime and only displays the date.  it always displays the uninitialized time like from the VCR era  12:00  (blinks on/off)

    As you wish.  Below is a list of Date types bound to a GridView, one column is formatted the other is not.   Keep in mind, this is the forth working code example that illustrates how to format a date.  Share all your relevant code if you are still having problems after reviewing the code sample below.  The community needs the GridView markup, model, and any code that populates the model.  This source information will help the community help you fix your code.

    Public Class GridViewModel
        Public Property TestDate As Date
    End Class
    Public Class GridViewDemo
        Inherits System.Web.UI.Page
    
        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not Page.IsPostBack Then
                PopulateStudentGrid()
            End If
        End Sub
    
        Protected Sub PopulateStudentGrid()
            Dim DateAndTime As DateTime = DateTime.Now
    
            Dim List As New List(Of GridViewModel)
            List.Add(New GridViewModel With {.TestDate = "1/1/2020"})
            List.Add(New GridViewModel With {.TestDate = #1/31/2020#})
            List.Add(New GridViewModel With {.TestDate = New Date(2020, 2, 2, 6, 10, 25)})
            List.Add(New GridViewModel With {.TestDate = DateAndTime})
    
            GridViewDemo.DataSource = List
            GridViewDemo.DataBind()
        End Sub
    
    End Class
    <%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="GridViewDemo.aspx.vb" Inherits="VbWebApplication.GridViewDemo" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
        <asp:GridView ID="GridViewDemo" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Formatted Test Date">
                    <EditItemTemplate>
                        <asp:TextBox ID="fTestDate" runat="server" Text='<%# Bind("TestDate") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="fTestDate" runat="server" Text='<%# Bind("TestDate", "{0:MM/dd/yyyy}") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Test Date No Format">
                    <EditItemTemplate>
                        <asp:TextBox ID="TestDate" runat="server" Text='<%# Bind("TestDate") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="TestDate" runat="server" Text='<%# Bind("TestDate") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </asp:Content>
    

    Tuesday, February 4, 2020 12:02 PM