简体   繁体   English

在isDate()或Datetime.TryParse中指定CultureInfo

[英]specifying CultureInfo in isDate() or Datetime.TryParse

I need to identify if a string is a date in format dd.mm.yyyy . 我需要确定字符串是否为dd.mm.yyyy格式的dd.mm.yyyy

However the application is running on systems with different language settings. 但是,该应用程序在具有不同语言设置的系统上运行。 Thus using isDate or TryParse on a 'valid' string returns true on a german system (since those functions use CultureInfo.CurrentCulture ) and return false on a system with ie english system settings. 因此,在“有效”字符串上使用isDateTryParse在德语系统上返回true(因为这些函数使用CultureInfo.CurrentCulture ),而在具有英语系统设置的系统上返回false。

Is there a function that checks if a string is a valid date with respect to a specified CultureInfo? 是否有一个功能可以检查字符串是否相对于指定的CultureInfo有效日期?

Of course i can always use regex to verify this, but i can't imagine that this is necessary. 当然,我总是可以使用正则表达式来验证这一点,但是我无法想象这是必要的。

If you know the format of the string and this won't change you should use DateTime.TryParseExact using the InvariantCulture 如果您知道字符串的格式并且不会更改,则应使用InvariantCulture使用DateTime.TryParseExact

Imports System.Globalization

Dim dateString As String = "31.12.1901"
Dim dateValue As Date
Dim dateFormat As String = "dd.MM.yyyy"

If DateTime.TryParseExact(dateString, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, dateValue) Then
    'In the format expected
Else
    'NOT in the format expected
End If

Seems like i missed an overload of the TryParse Method: 好像我错过了TryParse方法的重载:

Dim myculture As New System.Globalization.CultureInfo("en-US")
myculture.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy"
myculture.DateTimeFormat.LongDatePattern = "dd/MM/yyyy"

If DateTime.TryParse("27/10/2010", myculture, Globalization.DateTimeStyles.None, New DateTime) Then

'Currect Date

End If

works perfectly fine. 工作完美。 (See http://forums.asp.net/t/1443698.aspx?in+ASP+NET+vb+IsDate+function+is+working+wrongly+ for details) (有关详细信息,请参见http://forums.asp.net/t/1443698.aspx?in+ASP+NET+vb+IsDate+function+is+working+wrongly+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM