sarsnake
sarsnake

Reputation: 27703

Getting the difference of two DateTime instances in milliseconds

What would be a proper fool-proof way of doing so? I am using ASP.NET MVC 3.

Upvotes: 5

Views: 14826

Answers (5)

Erçin Dedeoğlu
Erçin Dedeoğlu

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

NominSim
NominSim

Reputation: 8511

Subtraction would be my choice...

DateTime earlier = DateTime.Now;
// ...
DateTime later = DateTime.Now;
double result = (later - earlier).TotalMilliseconds;

Upvotes: 0

Eric Petroelje
Eric Petroelje

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

mellamokb
mellamokb

Reputation: 56769

(datetime2 - datetime1).TotalMilliseconds

Upvotes: 7

Jim Bolla
Jim Bolla

Reputation: 8295

        DateTime a = ...
        DateTime b = ...
        var ms = a.Subtract(b).TotalMilliseconds;

Upvotes: 11

Related Questions