Home > Enterprise >  C# - How can I check if DateTime has time
C# - How can I check if DateTime has time

Time:01-27

How can I validate if a give DateTime has actual time not just the default midnight time (00:00:00).

DateTime.TryParse("2022-11-01T14:52:17", out DateTime withTime1); // has time
DateTime.TryParse("2022-11-01T00:00:01", out DateTime withTime2); // has time
DateTime.TryParse("2022-11-01T00:00:00", out DateTime noTime ); // doesn't have time

CodePudding user response:

None of what you posted are DateTime values. They are strings. I'll answer the question you actually asked though:

if (myDateTime.TimeOfDay == TimeSpan.Zero)
{
    // Time is midnight.
}
else
{
    // Time is not midnight.
}

CodePudding user response:

From your example it depends if you want to verify that as a string or not

as a string you could do something like this

if(Datetime.toString().Split('T')[1] == "00:00:00")
    return false; //"no time" per your explanation
else
    return true; //time
  • Related