简体   繁体   English

使用DateTime.parseextract时出错

[英]Error while using DateTime.parseextract

I have a textbox - DateOfBirth I follow following steps from validating data to saving it in database. 我有一个文本框-DateOfBirth我遵循以下步骤,从验证数据到将其保存到数据库中。

Step 1: When I submit text, I validate if date is in correct format(dd/mm/yyyy): 步骤1:提交文字时,我会验证日期是否采用正确的格式(dd / mm / yyyy):

string Pattern = @"^(0?[1-9]|[12][0-9]|3[01])[/](0?[1-9]|1[012])[/](19|20)\d\d";

Step 2: If format is correct, I convert input value of textbox to datetime format: 步骤2:如果格式正确,则将文本框的输入值转换为datetime格式:

IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
DOB = DateTime.ParseExact(txtDOB.Value, "dd/mm/yyyy", theCultureInfo);

Step 3: Then I send value to database and save as it is in my table. 步骤3:然后,我将值发送到数据库并保存在表中。

I got an issue here: 我在这里遇到一个问题:
For date "04/04/2012" everything works fine. 对于日期“ 04/04/2012”,一切正常。
But if I submit date "4/04/2012" or "04/4/2012", the step 2 throws an exception: 但是,如果我提交日期“ 4/04/2012”或“ 04/4/2012”,则第2步会引发异常:

String was not recognized as a valid DateTime.

How do I handle this issue ? 我该如何处理?

Should I escape step 2 and do conversion in database query instead ??? 我应该跳过步骤2并在数据库查询中进行转换吗?

because the method expects that you have two places for the date and you only supplied one value, so to solve your problem, remove one d in ParseExact format. 因为该方法期望该日期有两个位置,并且只提供了一个值,所以要解决您的问题,请以ParseExact格式删除一个d

IFormatProvider theCultureInfo = new System.Globalization.CultureInfo("en-GB", true);
DOB = DateTime.ParseExact(txtDOB.Value, "d/M/yyyy", theCultureInfo);

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

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