获取两个DateTime实例的差异(以毫秒为单位)

时间:2021-11-11 21:31:50

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

这样做的适当的万无一失的方法是什么?我正在使用ASP.NET MVC 3。

5 个解决方案

#1


11  

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

#2


6  

(datetime2 - datetime1).TotalMilliseconds

#3


4  

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)

#4


0  

Subtraction would be my choice...

减法将是我的选择......

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

#5


0  

    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;
    }

#1


11  

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

#2


6  

(datetime2 - datetime1).TotalMilliseconds

#3


4  

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)

#4


0  

Subtraction would be my choice...

减法将是我的选择......

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

#5


0  

    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;
    }