我正在测试一段代码以查看规则是否每次都有效,所以我制作了一个简短的控制台应用程序,其中包含 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 |-> 检查是否失败,如果为真则使用不同的格式进行第二次解析 -> 更改格式和 .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");
请您参考如下方法:
but I cannot figure out how to check if the first parse fails in order to perform the second one
代替 DateTime.ParseExact 使用 DateTime.TryParseExact这将返回一个 bool 指示解析是否成功。
DateTime ModEndPeriod;
if (!DateTime.TryParseExact(GetEndPeriod,
format,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out ModEndPeriod))
{
//parsing failed
}
您还可以使用多种格式进行解析,使用 DateTime.TryParse overload它采用一系列格式:
string[] formatArray = new [] { "dd MMMM yyyy","MMMM dd yyyy"};
DateTime ModEndPeriod;
if (!DateTime.TryParseExact(GetEndPeriod,
formatArray,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out ModEndPeriod))
{
//parsing failed
}
