如何使用vb.net获取子字符串日期(年)?

Ama*_*nMJ 2 vb.net

我一直这样做,是否有可能在日期时间获得中间字符串.

示例:

基本上我的字符串返回'12/23/2015 12:00:00 AM'.

但是,我想要的实际上是2015年的"15".

我一直在用'strDate = strDate.Substring(0,9)'之类的东西,

当日期是这样的'1/2/2015 12:00:00 AM'时有时会让我错

有人可以帮我这个,我不确定我们是否可以得到中间.

Tim*_*ter 6

不要使用字符串方法,使用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
Run Code Online (Sandbox Code Playgroud)

更新:使用CultureInfo.InvariantCulture和您甚至不需要使用的格式TryParseExact,您可以立即使用Parse/ TryParse:

DateTime.TryParse(str, CultureInfo.InvariantCulture, DateTimeStyles.None, dt) 
Run Code Online (Sandbox Code Playgroud)

MSDN:自定义日期和时间格式字符串,"yy"自定义格式说明符