简体   繁体   中英

C# - How can I check if DateTime has time

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

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.
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM