How to compare two DateTime to seconds?
If both the date/time strings are in ISO 8601 format (YYYY-MM-DD hh:mm:ss) you can compare them with a simple string compare, like this: a = '2019-02-12 15:01:45.145' b = '2019-02-12 15:02:02.022' if a < b: print('Time a comes before b.
The timedelta represents a duration which is the difference between two-time to the microsecond resolution. To get a time difference in seconds, use the timedelta. total_seconds() methods. Multiply the total seconds by 1000 to get the time difference in milliseconds.
var date1 = DateTime.Now; var date2 = new DateTime (1992, 6, 6); var seconds = (date1 - date2).TotalSeconds;
Do you mean comparing two DateTime
values down to the second? If so, you might want something like:
private static DateTime RoundToSecond(DateTime dt) { return new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second); } ... if (RoundToSecond(dt1) == RoundToSecond(dt2)) { ... }
Alternatively, to find out whether the two DateTimes are within a second of each other:
if (Math.Abs((dt1 - dt2).TotalSeconds) <= 1)
If neither of these help, please give more detail in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With