我有一个单一的字符串变量,存储着可能是完整日期或部分日期的内容:
1)完整日期:2010年12月12日上午12:33
2)部分日期:上午12:33(没有日期字段,只有时间)
我正在尝试找出最佳方法来解析该字符串,以确定字符串是否缺少日期字符串。原因是,如果日期丢失,我的代码将在字符串末尾附加默认日期(例如1900年1月1日)。请注意,时间可能以各种格式显示。
更新-我针对此问题的特定解决方案。
正如所有“帖子”所述,这个问题有多种答案,我最终使用了以下方法,并希望它能帮助其他人*:
public DateTime ProcessDateAndTime(string dateString)
{
string dateAndTimeString = dateString;
string[] timeFormats = new string[]
{
"hh:mm tt", "hh:mm:ss tt",
"h:mm tt", "h:mm:ss tt",
"HH:mm:ss", "HH:mm", "H:mm"
};
// check to see if the date string has a time only
DateTime dateTimeTemp;
if (DateTime.TryParseExact(dateString, timeFormats,
CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out dateTimeTemp))
{
// setting date to 01/01/1900
dateAndTimeString = new DateTime(1900, 1, 1).ToShortDateString() + " " + dateString;
}
return DateTime.Parse(dateAndTimeString);
}
*注意:此方法基于一个假设,即在应用程序中仅使用特定数量的时间格式,并且保证传递了正确格式的日期和时间或仅时间字符串(进行预验证以删除垃圾文本)。