我一直在这样做,是否可以获取日期时间中的中间字符串。
示例:
基本上我的字符串返回“12/23/2015 12:00:00 AM”。
但是,我想要的实际上是 2015 年的“15”。
我一直在使用类似 'strDate = strDate.Substring(0, 9)',
当日期类似于“1/2/2015 12:00:00 AM”时,有时会返回错误
有人可以帮我解决这个问题吗,我不确定我们是否可以得到中间。
最佳答案
不要为此使用字符串方法,请使用DateTime.TryParseExact
:
Dim str = "12/23/2015 12:00:00 AM"
Dim dt As DateTime
If DateTime.TryParseExact(str, "MM'/'dd'/'yyyy hh:mm:ss tt", Globalization.CultureInfo.InvariantCulture, Globalization.DateTimeStyles.None, dt) Then
Dim yearOnly As String = dt.ToString("yy") ' 15
End If
更新:使用 CultureInfo.InvariantCulture
和这种格式,您甚至不需要使用 TryParseExact
,您可以使用 Parse
/立即尝试解析
:
DateTime.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
MSDN:Custom Date and Time Format Strings, The "yy" Custom Format Specifier
关于vb.net - 如何使用 vb.net 获取子字符串日期(年份)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30864933/