Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract a datetime from another datetime?

Tags:

c#

.net

datetime

How do I subtract two DateTime values from another DateTime value and have the result saved to a double?

like image 971
Siva Avatar asked Mar 03 '11 05:03

Siva


People also ask

Can you subtract two datetime objects?

Subtraction of two datetime objects in Python: It is allowed to subtract one datetime object from another datetime object. The resultant object from subtraction of two datetime objects is an object of type timedelta.

When you subtract one datetime variable from another datetime variable you get?

In . NET, if you subtract one DateTime object from another, you will get a TimeSpan object.

Can we subtract two datetime in Python?

Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format . To get the difference between two dates, subtract date2 from date1. A result is a timedelta object.


4 Answers

In .NET, if you subtract one DateTime object from another, you will get a TimeSpan object. You can then use the Ticks property on that TimeSpan object to get the number of ticks between the two DateTime objects. However, the ticks will be represented by a Long, not a Double.

DateTime date1; DateTime date2; Long diffTicks = (date2 - date1).Ticks; 

There are other interesting properties on the TimeSpan object like TotalMilliseconds and TotalMinutes and things like that which can help you out, and may be more what you are looking for.

like image 199
Brandon Montgomery Avatar answered Sep 30 '22 11:09

Brandon Montgomery


DateTime startTime = DateTime.Now;  DateTime endTime = DateTime.Now.AddSeconds( 75 );   TimeSpan span = endTime.Subtract ( startTime );  Console.WriteLine( "Time Difference (seconds): " + span.Seconds );  Console.WriteLine( "Time Difference (minutes): " + span.Minutes );  Console.WriteLine( "Time Difference (hours): " + span.Hours );  Console.WriteLine( "Time Difference (days): " + span.Days ); 
like image 20
sajoshi Avatar answered Sep 30 '22 10:09

sajoshi


I think this is what you need.

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.UtcNow;

var result = d1 - d2;

double dResult = result.Ticks;
like image 44
Razor Avatar answered Sep 30 '22 09:09

Razor


Use DateTime.Subtract which will return TimeSpan , then use TotalSeconds property of the result which is of type double.

like image 25
Nikhil Vaghela Avatar answered Sep 30 '22 11:09

Nikhil Vaghela