How to remove 00:00:00 from a Date in VB.Net?
-
25-06-2021 - |
質問
I have a datatable (returned by database using dataadaptor) with a DateOfBirth
field with 00:00:00
at the end of date of birth. I want to remove those 00:00:00 so I wrote a function but it doesn't do the job and I don't know why. Can anyone suggest to me how to remove the 00:00:00
from DateOfBirth
. I don't have permission to the database or the stored procedure.
Dim DOB As New DateTime
Dim newDob As String = ""
For Each x In dt.Rows
If x("DateOfBirth") <> String.Empty AndAlso IsDate(x("DateOfBirth")) Then
DOB = CDate(x("DateOfBirth"))
newDob = DOB.ToString("dd/MM/yyyy")
x("DateOfBirth") = newDob
End If
Next
解決
You can't remove the 00:00:00
from a date value, just from a date string. You can remove it when showing a date string by ToString("dd/MM/yyyy")
as you did, but x("DateOfBirth")
is a date value (as written in your if statement), and it measures the ticks (10 pow -7 of a second) from 1/1/1970 (sql datetime
) or 1/1/0001 (sql datetime2
or c# DateTime
). A date value doesn't have any string representation, only when you convert it to a string.
他のヒント
A DateTime
entry in your datarow
is a blob of binary data in practice. The 00:00:00
is just the string representation of it. What you are doing is putting 21/1/1978
into the date field, but as far as the computer is concerned this is the same date as 21/1/1978 00:00:00
so what you are doing has no effect.
What you should be doing is adjusting the display of the date when you are outputting it to a string wherever you are viewing it. There you can use the .ToString("dd/MM/yyyy")
to format it as you want.