我遇到了一个问题.我从数据库中获取日期时间字符串,其中一些日期时间字符串不包含时间.但至于新要求,每个日期时间字符串应该包含这样的时间,
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);
Run Code Online (Sandbox Code Playgroud)
但这仅适用于No 1)类型时间戳.我可以知道如何实现此任务,如何检测此日期时间字符串中是否存在时间元素.非常感谢你 :)
可能的匹配 如何验证"日期和时间"字符串是否只有时间?
信息提供的三个答案Arun Selva Kumar,Guru Kara,Patipol Paripoonnanonda是正确的,并检查的时间和我的服务宗旨.但我选择Guru Kara的答案仅仅取决于易用性和他给出的解释.非常感谢:)非常感谢大家:)
Gur*_*ara 21
日期时间组件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");
}
Run Code Online (Sandbox Code Playgroud)
试试这个,
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
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用此处列出的其他格式说明符,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;
}
Run Code Online (Sandbox Code Playgroud)
这种方法:
TimeOfDay指示午夜或没有明确时间时搜索字符串;和限制: