2013-04-09 127 views
12

我遇到了问题。我正在从数据库获取日期时间字符串,并且这些日期时间字符串中的一些不包含时间。但作为新的要求每一个日期时间字符串应该包含的时间,像这样,检查日期时间字符串是否包含时间

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); 

但对于没有1)型时间戳这仅适用。请让我知道如何实现这个任务,了解如何检测日期时间字符串中是否存在时间元素。非常感谢你:)

可能匹配 How to validate if a "date and time" string only has a time?

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

回答

12

日期时间部件TimeOfDay是你需要什么。

MSDN says “与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"); 
} 
+0

嘿谢谢你的回复:)我会通过n回发:) – 2013-04-09 05:28:30

+2

-1:此方法失败的任何日期时间字符串与指定的午夜时间;例如对于“2015-02-26T00:00”我期望得到“有时间”,但是System.DateTime.Parse(“2015-02-26T00:00”)。TimeOfDay.TotalSeconds的计算结果为0.0。 – 2015-02-26 10:22:34

+0

在第一句中,该方法的名称拼写错误。我试图编辑它,但stackoverflow用户界面说,编辑必须至少有六个字符。另外,我同意Kasper van den Berg所说的答案不符合要求。 – 2015-11-04 17:08:15

9

试试这个,

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

+0

嘿thanx的答复:)我会尝试这n个后回来:) – 2013-04-09 04:52:30

+0

如果字符串不是约会,否则你将给出错误的答案。您需要使用另一个DateTime.TryParseExact作为日期格式。 – Akanksha 2013-04-09 05:06:20

+0

嘿我试过这个,但它总是给出错误信息?你知道吗? 'string a =“08/04/2013 17:34:00”; DateTime myDate; (DateTime.TryParseExact(a,“dd/MM/yyyy hh:mm:ss”, CultureInfo.InvariantCulture,DateTimeStyles.None,out myDate)) { MessageBox.Show(“Correct”); //字符串有日期和时间 } else { MessageBox.Show(“Error”); //字符串只有日期部分 }' – 2013-04-09 05:09:56

-1

的日期和时间总是用空格分开吧。最简单的方法是:

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 
} 

希望这有助于!

+0

嗨thanx回复我会检查这个并发回:) – 2013-04-09 05:28:13

+0

你有机会尝试它吗?请告诉我。 – Pat 2013-04-10 05:04:05

+0

hey..hi..sorry为延迟..我选择了一个答案,我解释了为什么在问题本身..非常感谢帮助:)非常感谢。 – 2013-04-11 10:19:44

2

结合Guru KaraPatipol Paripoonnanonda的答案与。在净全球化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的方法简单和优雅。
0

这就是我现在要做的。这可能并不完美,但可能比考虑任何上午12点的日期时间没有时间更好。前提是,如果我在最终解决全时间规范时会解析它是否仅仅是一个日期,但如果它已经有一个时间组件则会失败。

我不得不假设没有一些有效的日期/时间有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)); 
    } 
} 
相关问题