ASP.Net中的日期差异

时间:2009-04-28 15:58:50

标签: c# .net

如何在date中获得ASP.NET C#差异?

E.g:

d1= 28/04/2009 09:26:14
d2= 28/04/2009 09:28:14

DateDiff = d2 - d1

6 个答案:

答案 0 :(得分:11)

我认为你可以通过以下方式实现:

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);

TimeSpan t = d1 - d2;

答案 1 :(得分:4)

const string DateFormat = "dd/MM/yyyy hh:mm:ss";

DateTime d1 = DateTime.ParseExact("28/04/2009 09:26:14", DateFormat, null);
DateTime d2 = DateTime.ParseExact("28/04/2009 09:28:14", DateFormat, null);

TimeSpan dateDiff = d2 - d1;

string duration = string.Format("The time difference is: {0}", dateDiff);

答案 2 :(得分:3)

Subtract类上有一个实例方法DateTime,它返回TimeSpanSee article

DateTime now = DateTime.Parse("2009-04-28");  
DateTime newyear = DateTime.Parse("2009-01-01");  
TimeSpan difference = now.Subtract(newyear);

答案 3 :(得分:1)

查看TimeSpan

答案 4 :(得分:1)

            Dim d1, d2 As Date
            Dim intElapsedDays As Integer
            Dim tspDif As TimeSpan
            tspDif = d2 - d1
            intElapsedDays = tspDif.Days

应该为d1和d2指定值

答案 5 :(得分:0)

这取决于输入格式的时间戳。例如,如果是unix时间戳,则下面的代码将枚举期间信息:

        int TimestampFrom = 1546336800; //2019.1.1 10:00
        int TimestampTo = 1547555400;   //2019.1.15 12:30
        DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        long dateFromunixTimeStampInTicks = (long)(TimestampFrom * TimeSpan.TicksPerSecond);
        DateTime dateFrom = new DateTime(unixStart.Ticks + dateFromunixTimeStampInTicks, System.DateTimeKind.Utc);
        long dateTounixTimeStampInTicks = (long)(TimestampTo * TimeSpan.TicksPerSecond);
        DateTime dateTo = new DateTime(unixStart.Ticks + dateTounixTimeStampInTicks, System.DateTimeKind.Utc);
        TimeSpan Period = dateTo - dateFrom;
        int days = Convert.ToInt32(Period.TotalDays);       //>14
        int hours = Convert.ToInt32(Period.TotalHours);     //>338
        int seconds = Convert.ToInt32(Period.TotalSeconds); //>1218600

如果源日期格式为正常的DateTime,则对日期进行足够的简单减法将返回包含所有期间信息的TimeSpan结构。

答案:“如何获取两个日期时间之间的间隔(时间戳)[重复]” 这不是重复项。