check if date time string contains time

后端 未结 5 1796
鱼传尺愫
鱼传尺愫 2021-02-06 23:37

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

5条回答
  •  花落未央
    2021-02-07 00:25

    The date time components TimeOfDay is what you need.

    MSDN says "Unlike the Date property, which returns a DateTime value that represents a date without its time component, the TimeOfDay property returns a TimeSpan value that represents a DateTime value's time component."

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

提交回复
热议问题