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

问题描述:

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

I have run into an issue. I'm obtaining a date time string from the database and and some of these date time strings does not contain time. But as for the new requirement every date time string should contain the time like so,

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

日期可以采用任何格式,后跟时间为 24hr 表示法。

Date can be in any format followed by the time in 24hr notation.

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

I tried to detect the existence of time via the following code,

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)输入时间戳记。请问如何检测此日期时间字符串中是否存在时间元素,请问如何实现此任务。非常感谢:)

But this only works for the No 1) type timestamps. May I please know how to achieve this task on how to detect if the time element exist in this date time string. Thank you very much :)

可能的匹配
如何验证日期和时间是否为字符串只有一个时间?

INFO Arun Selva Kumar $提供的三个答案c $ c>, Guru Kara Patipol Paripoonnanonda 都是正确的,可以检查时间,符合我的目的。但是我选择 Guru Kara 的答案仅是出于易用性以及他给出的解释。非常感谢:)非常感谢大家:)

INFO the three answers provided by Arun Selva Kumar,Guru Kara,Patipol Paripoonnanonda are all correct and checks for the time and serves my purpose. But I select Guru Karas answer solely on ease of use and for the explanation he has given. Thank you very much :) very much appreciated all of you :)

日期时间部分 TimeOfDay 是您所需要的。

The date time components TimeOfDay is what you need.

MSDN说与Date属性不同,该属性返回代表不带时间成分的日期的DateTime值,而TimeOfDay属性返回代表DateTime值的时间成分的TimeSpan值。

这里是考虑所有情况的示例。

由于您确定格式,因此可以使用 DateTime.Parse 否则请使用 DateTime.TryParse

Here is an example with consideration of all your scenarios.
Since you are sure of the format you can use DateTime.Parse else please use 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");
}