【发布时间】:2014-07-02 17:15:14
【问题描述】:
我正在测试一段代码以查看规则是否每次都有效,所以我只是制作了一个简短的控制台应用程序,它有 1 个字符串作为输入值,我可以随时替换它。
string titleID = "document for the period ended 31 March 2014";
// the other variation in the input will be "document for the period
// ended March 31 2014"
我正在做的是从中提取特定部分(取决于它是否包含特定单词 - nvm 详细信息,存在一致性,因此我不担心这种情况)。之后,我将在特定位置之后取出字符串的其余部分以执行 DateTime.ParseExact
最终我需要弄清楚如何检查第一个 DateTime.ParseExact 是否失败 然后使用不同的自定义格式执行第二次尝试。
看起来是这样的:
if(titleID.Contains("ended "))
{
// take the fragment of the input string after the word "ended"
TakeEndPeriod = titleID.Substring(titleID.LastIndexOf("ended "));
// get everything after the 6th char -> should be "31 March 2014"
GetEndPeriod = TakeEndPeriod.Substring(6);
format2 = "dd MMMM yyyy"; // custom date format which is mirroring
// the date from the input string
// parse the date in order to convert it to the required output format
try
{
DateTime ModEndPeriod = DateTime.ParseExact(GetEndPeriod, format2, System.Globalization.CultureInfo.InvariantCulture);
NewEndPeriod = ModEndPeriod.ToString("yyyy-MM-ddT00:00:00Z");
// required target output format of the date
// and it also needs to be a string
}
catch
{
}
}
// show output step by step
Console.WriteLine(TakeEndPeriod);
Console.ReadLine();
Console.WriteLine(GetEndPeriod);
Console.ReadLine();
Console.WriteLine(NewEndPeriod);
Console.ReadLine();
在我尝试不同的输入字符串 f.eg. 之前,一切正常。 "截至 2014 年 3 月 31 日期间的文件"
所以在这种情况下,如果想解析“2014 年 3 月 31 日”,我必须将自定义格式切换为 “MMMM dd yyyy”,我这样做并且它有效,但我不知道如何检查第一个解析是否失败以执行第二个解析。
第一次解析 -> 成功 -> 改变格式和 .ToString |-> 检查是否失败,如果为 true,则使用不同的格式进行第二次解析 -> 更改格式和 .ToString
我试过了
if (String.IsNullOrEmpty(NewEndPeriod))
{ do second parse }
或者
if (NewEndPeriod == null)
{ do second parse }
但我在 Console.WriteLine(NewEndPeriod); 处得到一个空白结果
有什么想法可以解决这个问题吗?
** 编辑:**
在这里添加一个我得到的替代答案,它使用 Parse 而不是 TryParseExact,因为 Parse 将处理这两种格式变化而无需指定它们
DateTime DT = DateTime.Parse(GetEndPeriod);
//The variable DT will now have the parsed date.
NewEndPeriod = DT.ToString("yyyy-MM-ddT00:00:00Z");
【问题讨论】:
-
“最终我需要弄清楚如何检查第一次 DateTime.ParseExact 是否失败,然后使用不同的自定义格式执行第二次尝试。” 您也可以使用
ParseExact的重载接受string[]用于所有允许的格式。除此之外,TryParse方法是您正在寻找的。永远不要:catch{ } -
使用 tryparseexact 而不是 parseexact