检查日期时间字符串是否包含时间

我遇到了一个问题。 我从数据库中获取日期时间字符串,其中一些日期时间字符串不包含时间。 但至于新要求,每个日期时间字符串应该包含这样的时间,

1) 1980/10/11 12:00:01 2) 2010/APRIL/02 17:10:00 3) 10/02/10 03:30:34

日期可以是任何格式,后跟24hr表示法的时间。

我试图通过以下代码检测时间的存在,

 string timestamp_string = "2013/04/08 17:30"; DateTime timestamp = Convert.ToDateTime(timestamp_string); string time =""; if (timestamp_string.Length > 10) { time = timestamp.ToString("hh:mm"); } else { time = "Time not registered"; } MessageBox.Show(time); 

但这仅适用于No 1)类型的时间戳。 我可以知道如何实现此任务,如何检测此日期时间字符串中是否存在时间元素。 非常感谢你 :)

可能的匹配 如何validation“日期和时间”字符串是否只有时间?

信息Arun Selva KumarGuru KaraPatipol Paripoonnanonda提供的三个答案都是正确的,并检查时间并满足我的目的。 但我选择Guru Kara的答案完全取决于易用性和他给出的解释。 非常感谢:)非常感谢大家:)

日期时间组件TimeOfDay是您所需要的。

MSDN说“与Date属性不同,Date属性返回表示没有时间组件的日期的DateTime值,TimeOfDay属性返回表示DateTime值的时间组件的TimeSpan值。”

这是一个考虑所有场景的示例。
由于您确定可以使用DateTime.Parse的格式,请使用DateTime.TryParse

 var dateTime1 = System.DateTime.Parse("1980/10/11 12:00:00"); var dateTime2 = System.DateTime.Parse("2010/APRIL/02 17:10:00"); var dateTime3 = System.DateTime.Parse("10/02/10 03:30:34"); var dateTime4 = System.DateTime.Parse("02/20/10"); if (dateTime1.TimeOfDay.TotalSeconds == 0) { Console.WriteLine("1980/10/11 12:00:00 - does not have Time"); } else { Console.WriteLine("1980/10/11 12:00:00 - has Time"); } if (dateTime2.TimeOfDay.TotalSeconds == 0) { Console.WriteLine("2010/APRIL/02 17:10:00 - does not have Time"); } else { Console.WriteLine("2010/APRIL/02 17:10:00 - Has Time"); } if (dateTime3.TimeOfDay.TotalSeconds == 0) { Console.WriteLine("10/02/10 03:30:34 - does not have Time"); } else { Console.WriteLine("10/02/10 03:30:34 - Has Time"); } if (dateTime4.TimeOfDay.TotalSeconds == 0) { Console.WriteLine("02/20/10 - does not have Time"); } else { Console.WriteLine("02/20/10 - Has Time"); } 

试试这个,

 DateTime myDate; if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate)) { //String has Date and Time } else { //String has only Date Portion } 

您可以尝试使用此处列出的其他格式说明符, http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

将Guru Kara和Patipol Paripoonnanonda的答案与.net全球化API相结合,可以得到:

 bool HasExplicitTime(DateTime parsedTimestamp, string str_timestamp) { string[] dateTimeSeparators = { "T", " ", "@" }; string[] timeSeparators = { CultureInfo.CurrentUICulture.DateTimeFormat.TimeSeparator, CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator, ":"}; if (parsedTimestamp.TimeOfDay.TotalSeconds != 0) return true; string[] dateOrTimeParts = str_timestamp.Split( dateTimeSeparators, StringSplitOptions.RemoveEmptyEntries); bool hasTimePart = dateOrTimeParts.Any(part => part.Split( timeSeparators, StringSplitOptions.RemoveEmptyEntries).Length > 1); return hasTimePart; } 

这种方法:

  • 检测明确的午夜时间(例如“2015-02-26T00:00”);
  • 仅在TimeOfDay指示午夜或没有明确时间时搜索字符串; 和
  • 以.net可以解析的任何格式查找本地格式和任何非午夜时间的显式午夜时间。

限制:

  • 未检测到非文化本地格式的显式午夜时间;
  • 没有检测到少于两个部分的显式午夜时间; 和
  • 不像Guru Kara和Patipol Paripoonnanonda那样简单而优雅。

这就是我现在要做的事情。 它可能不完美,但可能比考虑任何12am日期时间更好,因为没有时间。 前提是如果我在最后添加一个完整的时间规范,它将解析它是否只是一个日期,但如果它已经有一个时间组件则会失败。

我不得不假设没有一些有效的日期/时间有7个非空白字符或更少。 似乎“1980/10”解析,但不是“1980/10 01:01:01.001”。

我已经包含了各种测试用例。 随意添加自己的,如果他们失败,请告诉我。

 public static bool IsValidDateTime(this string dateString, bool requireTime = false) { DateTime outDate; if(!DateTime.TryParse(dateString, out outDate)) return false; if (!requireTime) return true; else { return Regex.Replace(dateString, @"\s", "").Length > 7 && !DateTime.TryParse(dateString + " 01:01:01.001", out outDate); } } public void DateTest() { var withTimes = new[]{ "1980/10/11 01:01:01.001", "02/01/1980 01:01:01.001", "1980-01-01 01:01:01.001", "1980/10/11 00:00", "1980/10/11 1pm", "1980-01-01 00:00:00"}; //Make sure our ones with time pass both tests foreach(var date in withTimes){ Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date)); Assert.IsTrue(date.IsValidDateTime(true), String.Format("date: {0} does have time.", date)); } var withoutTimes = new[]{ "1980/10/11", "1980/10", "1980/10 ", "10/1980", "1980 01", "1980/10/11 ", "02/01/1980", "1980-01-01"}; //Make sure our ones without time pass the first and fail the second foreach (var date in withoutTimes) { Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date)); Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} doesn't have time.", date) ); } var bogusTimes = new[]{ "1980", "1980 01:01", "80 01:01", "1980T01", "80T01:01", "1980-01-01T01", }; //Make sure our ones without time pass the first and fail the second foreach (var date in bogusTimes) { DateTime parsedDate; DateTime.TryParse(date, out parsedDate); Assert.IsFalse(date.IsValidDateTime(), String.Format("date: {0} is valid. {1}", date, parsedDate)); Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} is valid. {1}", date, parsedDate)); } } 

日期和时间始终用空格键分隔。 最简单的方法是:

 if (timestamp_string.Split(' ').Length == 2) { // timestamp_string has both date and time } else { // timestamp_string only has the date } 

此代码假定日期始终存在。

如果你想进一步(如果日期不存在),你可以这样做:

 if (timestamp_string.Split(' ') .Select(item => item.Split(':').Length > 1) .Any(item => item)) { // this would work for any string format that contains date, for example: // 2012/APRIL/03 12:00:05 -> this would work // 2013/04/05 09:00:01 -> this would work // 08:50:45 2013/01/01 -> this would also work // 08:50:50 -> this would also work } else { // no date in the timestamp_string at all } 

希望这可以帮助!