c# - 根据文化将日期和时间正则表达式设置为 RegularExpressionValidator

标签 c# asp.net regex cultureinfo culture

<分区>

我面临着根据本地文化验证日期和时间的问题。

这是我的正则表达式验证器

  <asp:RegularExpressionValidator
       ID="regTime"
       ControlToValidate="txtTime"
       Display="Dynamic"
       Text="Invalid Time Format"
       ValidationExpression="^((1[012])|(0?[1-9])):([0-5][0-9]) ?([aApP][mM])$"
       runat="server">
 </asp:RegularExpressionValidator>

上述验证器验证了 en-en 文化的时间。

现在我正在开发一个需要能够处理每种文化的日期和时间格式的应用程序,我想要一个具体的解决方案来解决如何使用 RegularExpression 根据文化验证日期和时间。

例如,美国时间格式为 h:mm tt (01:20 PM),德国时间格式为 HH:mm (13:20)。

最佳答案

抱歉,这让我想起了一句流行的话:

Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.

无论如何,您不需要为此使用正则表达式。 .NET 的 DateTime 和 CultureInfo 最适合解决这个问题。创建您自己的自定义验证器,执行如下操作:

var usCulture = new CultureInfo("en-us");
DateTime.ParseExact("3:20 PM", usCulture.DateTimeFormat.ShortTimePattern, usCulture);

var germanCulture = new CultureInfo("de");
DateTime.ParseExact("13:20", germanCulture.DateTimeFormat.ShortTimePattern, germanCulture);

如果您想要返回值而不是异常,请使用 DateTime.TryParseExact

关于c# - 根据文化将日期和时间正则表达式设置为 RegularExpressionValidator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131758/

相关文章:

c# - 我想在关闭我的 UWP 应用程序之前存储一个 int 值

c# - 如何使用 SSIS 脚本任务 C# 2005 或 2008 解压缩包含多个文件的文件夹?

asp.net - 具有 2 个不同域的 mvc3 路由

asp.net - 如何 : Manupilate SharePoint:AspMenu control (Style-wise)

javascript - 正则表达式匹配具有不同数字和最小长度的数字

C# Linq 将元素添加到满足条件的对象列表中

c# - Visual Studio 2015 空白应用程序(通用 Windows): CS0731

asp.net mvc nhibernate 单元测试

regex - 使用sed将字符串逐行替换为正则表达式

regex - 删除 xml 文件中没有排序或唯一的重复连续行