C# 减去 2 个日期时间字段以获得剩余天数的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1905443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:45:17  来源:igfitidea点击:

subtract 2 datetime fields to get the days left difference

c#datetimetimespan

提问by Jobi

Would appreciate it if anyone can help me figure out to substract 2 datetime fields to get the days left difference.

如果有人能帮我找出减去 2 个日期时间字段以获得剩余天数,我将不胜感激。

回答by Myles

You should look at TimeSpan.

你应该看看TimeSpan

回答by rahul

Use

TimeSpan

时间跨度

DateTime departure = new DateTime(2010, 6, 12, 18, 32, 0);
DateTime arrival = new DateTime(2010, 6, 13, 22, 47, 0);
TimeSpan travelTime = arrival - departure;  

回答by Jesper Palm

DateTime dt1 = new DateTime(2009,01,01,00,00,00);
DateTime dt2 = new DateTime(2009,12,31,23,59,59);

int days = (dt2 - dt1).Days;

回答by John K

Number of Days Difference

天数差异

These answers take the number of days as an intfrom the System.TimeSpanstructure that is the result of subtracting two System.DateTimefields...

这些答案将天数作为减去两个字段的结果intSystem.TimeSpan结构System.DateTime......

Quick answer- gets the number of days difference.

快速回答- 获取天数差异。

        int numDaysDiff = date2.Subtract(date1).Days;

Alternate answer- uses Math.Abs to ensure it's not a negative number, just in case the dates might be supplied in either order.

替代答案- 使用 Math.Abs​​ 来确保它不是负数,以防万一日期可能以任一顺序提供。

        int numDaysDiff = Math.Abs( date2.Subtract(date1).Days );

Some sample data to finish it off using Systemnamespace:

一些示例数据以完成using System命名空间:

        // sample data
        DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddDays(10);

MSDN References (and more sample code ):

MSDN 参考(以及更多示例代码):

回答by Maxim Zaslavsky

This is very easy to do with C#. For comparing DateTimes, we have a class called TimeSpan. The TimeSpan structure, in this case, would be defined as the difference between your two datetimes.

这很容易用 C# 做到。为了比较 DateTimes,我们有一个名为TimeSpan的类。在这种情况下, TimeSpan 结构将定义为两个 datetime 之间的差异

Let's say that your DateTimes are called start and end.

假设您的日期时间称为开始和结束。

DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

We have established our DateTimes to June 14, 2009 and December 14, 2009.

我们已将日期时间设置为 2009 年 6 月 14 日和 2009 年 12 月 14 日。

Now, let's find the difference between the two. To do this, we create a TimeSpan:

现在,让我们找出两者之间的区别。为此,我们创建了一个 TimeSpan:

TimeSpan difference = end - start;

With this TimeSpan object, you can express the difference in times in many different ways. However, you specifically asked for the difference in days, so here's how you can get that:

使用这个 TimeSpan 对象,您可以用许多不同的方式表达时间的差异。但是,您特别要求天数差异,因此您可以通过以下方式获得:

Console.WriteLine("Difference in days: " + difference.Days);

Thus, the property is called TimeSpan.Days.

因此,该属性称为TimeSpan.Days



Final Code

最终代码

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

Console.WriteLine("Difference in days: " + difference.Days); //Extract days, write to Console.

For more information on using the TimeSpan structure, see this MSDN documentation(especially the C# examples).

有关使用 TimeSpan 结构的更多信息,请参阅此 MSDN 文档(尤其是 C# 示例)。

Hope I helped!

希望我有所帮助!

UPDATE:Some answers have suggested taking doing subtraction in one step, such as with:

更新:一些答案建议一步进行减法,例如:

int days = (dt2 - dt1).Days;

or

或者

int numDaysDiff = Math.Abs(date2.Subtract(date1).Days);

However, they are the same thing as in my answer, only shortened. This is because the DateTime.Subtract() method and the subtraction operator of DateTimes returns a TimeSpan, from which you can then access the amount of days. I have specifically used the longer approach in my code sample so that you clearly understand what is going onbetween your DateTime and TimeSpan objects and how it all works. Of course, the other approaches I just mentioned are fine, too.

但是,它们与我的回答相同,只是缩短了。这是因为DateTime.Subtract() 方法和 DateTimes 的减法运算符返回一个 TimeSpan,然后您可以从中访问天数。我在我的代码示例中专门使用了更长的方法,以便您清楚地了解DateTime 和 TimeSpan 对象之间发生的事情以及它们是如何工作的。当然,我刚才提到的其他方法也很好。

UPDATE #2:

更新#2:

A very similar question was asked before, and it can be found here. However, the main point of that question was why the code sample (which is essentially equivalent to that of all the answers) sometimesprovides an answer which is a day off. I think this is also important to this question.

之前有人问过一个非常相似的问题,可以在这里找到。但是,该问题的要点是为什么代码示例(基本上等同于所有答案的代码)有时会提供一个休息日的答案。我认为这对这个问题也很重要。

As the main answer to the other question suggests, you can use this code:

正如另一个问题的主要答案所暗示的那样,您可以使用以下代码:

int days = (int)Math.Ceiling(difference.TotalDays);

This code uses Math.Ceiling, which, according to MSDN, is:

此代码使用 Math.Ceiling,根据 MSDN,它是:

Returns the smallest integral value that is greater than or equal to the specified double-precision floating-point number.

返回大于或等于指定双精度浮点数的最小整数值。

How Do You Want to Count the Days?

你想如何计算天数?

Thus, we now have an issue with how you want to count the days. Do you want to count part of a day (such as .5 of a day) as:

因此,我们现在有一个关于如何计算天数的问题。您想将一天的一部分(例如一天的 0.5)计算为:

  • A full day- this would use Math.Ceiling to round up TimeSpan.TotalDays, so that you're counting started days.
  • Part of a day- you can just return the TimeSpan.TotalDays (not rounded) as a decimal (in the double datatype)
  • Nothing- you can ignore that part of a day and just return the TimeSpan.Days.
  • 一整天- 这将使用 Math.Ceiling 对 TimeSpan.TotalDays 进行四舍五入,以便您计算开始天数。
  • 一天的一部分- 您可以将 TimeSpan.TotalDays(未四舍五入)作为小数返回(在 double 数据类型中)
  • 什么都没有——你可以忽略一天的那一部分,只返回 TimeSpan.Days。

Here are code samples for the above:

以下是上述代码示例:

Counting as a full day(using Math.Ceiling() to round up):

计算为一整天(使用 Math.Ceiling() 来四舍五入):

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

int days = (int)Math.Ceiling(difference.TotalDays); //Extract days, counting parts of a day as a full day (rounding up).

Console.WriteLine("Difference in days: " + days); //Write to Console.

Counting as part of a day(NOT using Math.Ceiling(), instead leaving in decimal form as a part of a day):

作为一天的一部分计数(不使用 Math.Ceiling(),而是以十进制形式作为一天的一部分):

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

double days = difference.TotalDays; //Extract days, counting parts of a day as a part of a day (leaving in decimal form).

Console.WriteLine("Difference in days: " + days); //Write to Console.

Counting as nothing of a day(rounding down to the number of full days):

算作一天的零(四舍五入到全天数):

//establish DateTimes
DateTime start = new DateTime(2009, 6, 14);
DateTime end = new DateTime(2009, 12, 14);

TimeSpan difference = end - start; //create TimeSpan object

int days = difference.TotalDays; //Extract days, counting parts of a day as nothing (rounding down).

Console.WriteLine("Difference in days: " + days); //Write to Console.

回答by Vijay Balkawade

The easiest way out is, making use of TimeSpan(). This Subtract function will return you the difference between two dates in terms of time span. Now you can fetch fields like days, months etc. To access days you can make use of Here is the sample code;

最简单的方法是使用 TimeSpan()。此减法函数将返回两个日期在时间跨度方面的差异。现在您可以获取天数、月数等字段。要访问天数,您可以使用以下示例代码;

VB.Net code;

VB.Net代码;

    Dim tsTimeSpan As TimeSpan
    Dim ldDate1 as Date
    Dim ldDate2 as Date
      'Initialize date variables here
       tsTimeSpan = ldDate1 .Subtract(ldDate2)
       Dim NumberOfDays as integer = tsTimeSpan.days

C#.Net code;

C#.Net 代码;

    DateTime lDate1;
    DateTime lDate2;
    TimeSpan tsTimeSpan ;
    int NumberOfDays;
      //Initialize date variables here
      tsTimeSpan = ldDate1 .Subtract(ldDate2);
      NumberOfDays = tsTimeSpan.days;

回答by Mvg Developer

DateTime theDate = DateTime.Today;
int datediff = theDate.Subtract(expiryDate).Negate().Days;
if expiryDate > theDate then you get Negative value: -14
expiryDate is less than theDate then you get positive value: 14

You May obviously want this in a scenario such as

您可能显然希望在以下情况下使用它

  1. Send a Notification Email 14days before expiry
  2. Send another notification Email 14 days after expiry
  1. 在到期前 14 天发送通知电子邮件
  2. 到期后 14 天再发送一封通知电子邮件

You need a difference that could be negative value

您需要一个可能为负值的差异

回答by PatWill

To get the exact days ignoring the time section

要获得忽略时间部分的确切日期

    DateTime d1 = Convert.ToDateTime(DateTime.Now.ToShortDateString());
    DateTime d2 = Convert.ToDateTime(DateTime.Now.AddDays(46).ToShortDateString());

    var days = Convert.ToInt32(d2.Subtract(d1).TotalDays)