简体   繁体   中英

VB.Net - How to get GridView to only show Date from DateTime SQL column?

I have an SQL formula that I plan to use in an upcoming Web program developed in VB.NET, which will display the data obtained from my SQL formula in GridView.

There is a specific part of my SQL I'm having trouble with

select A.[Inv No], A.[Project No], 
cast([Record Date] as date)as [Date],   --This area is problem field
A.[Description], A.[Problem + Repair Details], 
A.[Status], convert(float, A.[Accumulative Stroke]) 
as [Accumulative Stroke],
convert(float, A.[Preventive Stroke]) 
as [Preventive Stroke], 
A.[PIC], A.[Measurement (OK/NG)] 
from [SQL].[dbo].[MAINT_ENTRY] A 

left join (select [Inv No], max(Date +' '+ Time) as [Record Date] 
from [SQL].[dbo].[MAINT_ENTRY] 
group by [Inv No]) B 

on A.[Inv No] = B.[Inv No]

where [Record Date] = Date +' '+ Time and 
[Problem + Repair Details] <> '""' 
Order by A.[Status], A.[Inv No], A.[Date]desc

[Record Date] is a column that merges the Date and Time column into a single merged column in order for me to get the very latest data to display in my program. Both of those fields need to be in datetime format in order for them to join.

I want the GridView to only show the Date in Record Date and since it is in datetime I tried using CAST to change the format as date .

Although it shows the correct result in SQL Management Studio, where I was simulating the results, it doesn't seem to want to play nice in VB.Net as the result I get still uses the datetime format. It deletes the time data but still keeps the time formatting.

22/4/2019 08:45:00 AM ---> 22/4/2019 12:00:00 AM

what seems to be the problem causing this?

You are trying to cast the Datetime directly in the SQL query, in order to do that instead of

cast([Record Date] as date)as [Date]

you should do it like this:

CONVERT(varchar(10), [Record Date], 103) as [Date]

As the CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) syntax specifies: Reference

If I am understanding your question, you are returning an object from some SQL server that has a DateTime field. You want to use VB to display just the date component.

In VB, there is a "Date" property to the DateTime object that you can use to display JUST the date component of the DateTime property. A simple code example:

Dim myDateTime as DateTime = now()
MessageBox.Show("Today's date is: " + myDateTime.Date)

If you need more of a reference, have a look at https://docs.microsoft.com/en-us/dotnet/api/system.datetime.date?view=netframework-4.8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM