Reputation: 27703
What would be a proper fool-proof way of doing so? I am using ASP.NET MVC 3.
Upvotes: 5
Views: 14826
Reputation: 5383
public static Int64 GetDifferencesBetweenTwoDate(DateTime newDate, DateTime oldDate, string type)
{
var span = newDate - oldDate;
switch (type)
{
case "tt": return (int)span.Ticks;
case "ms": return (int)span.TotalMilliseconds;
case "ss": return (int)span.TotalSeconds;
case "mm": return (int)span.TotalMinutes;
case "hh": return (int)span.TotalHours;
case "dd": return (int)span.TotalDays;
}
return 0;
}
Upvotes: 0
Reputation: 8511
Subtraction would be my choice...
DateTime earlier = DateTime.Now;
// ...
DateTime later = DateTime.Now;
double result = (later - earlier).TotalMilliseconds;
Upvotes: 0
Reputation: 60498
I'm thinking this should work. Since you asked for foolproof, I'm assuming you don't know which of the two is the later date :)
Math.Abs((date1 - date2).TotalMilliseconds)
Upvotes: 4
Reputation: 8295
DateTime a = ...
DateTime b = ...
var ms = a.Subtract(b).TotalMilliseconds;
Upvotes: 11