简体   繁体   中英

How to parse a date as iso in VB.NET

I am trying to parse a date in vb.net as below.

Dim EndDate As Date = Date.Now.ToString("yyyy-MM-dd")
If Date.TryParseExact(txtEndDate.Text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, EndDate) Then
  EndDate = txtEndDate.Text
Else
  txtEndDate.Text = EndDate
End If

I cannot understand why my code above outputs 00:00:00

DESIRED RESULT

If date input is not valid ISO date "yyyy-MM-dd" then

Set txtEndDate.Text and EndDate to date today as ** ISO .


EXAMPLE

if I pass in 2016-15-10

EndDate gets set to #10/15/2016 12:00:00 AM#

if I pass in asfd

EndDate gets set to #1/1/0001 12:00:00 AM#

Would you not just do this:

Dim EndDate As String = Date.Now.ToString("yyyy-M-d")
If Not Date.TryParseExact(txtEndDate.Text, "yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None, EndDate) Then
  txtEndDate.Text = Date.Now.ToString("yyyy-M-d")
End If

If it is successful then EndDate will be returned as expected however if not then just set to today as you were above.

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