Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two DateTime to seconds?

Tags:

c#

.net

How to compare two DateTime to seconds?

like image 562
Vlad Omelyanchuk Avatar asked Sep 28 '10 19:09

Vlad Omelyanchuk


People also ask

How can I compare two datetime strings?

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.

How do I calculate seconds between two times in python?

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.


2 Answers

var date1 = DateTime.Now; var date2 = new DateTime (1992, 6, 6);  var seconds = (date1 - date2).TotalSeconds; 
like image 128
Dan Abramov Avatar answered Sep 28 '22 02:09

Dan Abramov


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.

like image 29
Jon Skeet Avatar answered Sep 28 '22 03:09

Jon Skeet