从字符串到类型“日期”的转换无效。 [英] Conversion from string to type 'date' is not valid.

查看:566
本文介绍了从字符串到类型“日期”的转换无效。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要帮助字符串值来自文本框。

i不能使用datetimepicker,因为文本框包含其他值..



< b>我尝试过:



Need help the string value come from a textbox.
i cannot use datetimepicker because the textbox consist of other value..

What I have tried:

If ItemBox1.Text <> "" Then
           I1 = "20" & Mid(ItemBox1.Text, 16, 4) & "01"
           Dim I1Date As DateTime = DateTime.ParseExact(I1, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture)
           Dim dayApart As TimeSpan = Today.Subtract(I1Date)
           Dim diff As Double = dayApart.TotalDays
           If diff > expiryDate.Text Then
               lblmessage.Text = "*"
           Else
               'do nothing'
           End If
           'do nothing'
       End If

推荐答案

你应该使用Date.TryParseExact,下面就是一个例子。



You should use Date.TryParseExact, below is an example.

Dim enUS As New CultureInfo("en-US") 
      Dim dateString As String
      Dim dateValue As Date

      ' Parse date with no style flags.
      dateString = "20091223"
      If Date.TryParseExact(dateString, "yyyyMMdd", enUS, _
                            DateTimeStyles.None, dateValue) Then
         Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, _
                           dateValue.Kind)
      Else
         Console.WriteLine("'{0}' is not in an acceptable format.", dateString)
      End If





参考这个了解更多详情。


使用TryParseExact而不是ParseExact - 它返回一个布尔值,表明解析是好的还是坏的。如果不好,请将问题报告给用户,以便他们能够纠正并且不要继续。



你永远不应该依赖用户来做到正确:他们会打字一直都是错误,就像你和我一样。
Use TryParseExact instead of ParseExact - it returns a boolean value indicating that the parse was ok or bad. If it's bad, report the problem to the user so they can correct it and do not continue.

You should never rely on users to get it right: they make typing mistakes all the time, just like you and I do.


这篇关于从字符串到类型“日期”的转换无效。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆