简体   繁体   English

比较两个DATE并在c#中获取Days

[英]Compare two DATE and get Days in c#

Count Number of days by comapaing two date, When you want to compare two date like due Date and return date of a book in library then you can get no of days in this manner 计算comapaing两个日期的天数,如果你想比较两个日期,如期限日期和图书馆的书籍的返回日期,那么你可以用这种方式得到没有天数

        int TotalDay;
        DateTime due = OldDate;

        int day = due.Day;
        int nday = DateTime.Now.Day;
        int mnt = due.Month;
        int nmnt = DateTime.Now.Month;
        int yr = due.Year;
        int nyr = DateTime.Now.Year;
        if (nyr <= yr)
        {
            if (nmnt <= mnt)
            {
                if (nday > day)
                {
                    TotalDay = nday - day;
                }
            }
            else
            {
                TotalDay = nday - day;
                m = nmnt - mnt;
                TotalDay = d + (m * 30);
            }
        }
        else
        {
            TotalDay = nday - day;
            m = nmnt - mnt;
            TotalDay  = d + (m * 30);
            int y = nyr - yr;
            TotalDay  = d + (y * 365);
        }

Use TimeSpan 使用TimeSpan

TimeSpan ts = dateTime1 - dateTime2;

ts.TotalDays will give you the difference in number of days. ts.TotalDays将为您提供天数的差异。

In your case due is the due date and DateTime.Now is the current date. 在你的情况due在截止日期和DateTime.Now是当前日期。 You may use: 你可以使用:

TimeSpan ts = DateTime.Now - due;

//or 

TimeSpan ts = DateTime.Now.Subtract(due);

int NumberOfDays = ts.TotalDays;

You may look at TimeSpan.TotalDays property 您可以查看TimeSpan.TotalDays属性

You could use TimeSpan as shown in other answers - but you need to be careful about the time of day. 可以使用TimeSpan ,如其他答案中所示 - 但您需要注意一天中的时间。 Are you actually trying to think of these as dates or as dates with times? 您是否真的试图将这些视为日期或日期与时间? What about time zones? 时区怎么样? Are you using "local" DateTime values for both? 您是否正在使用“本地” DateTime值?

While DateTime can handle all of this, it leaves things unclear. 虽然DateTime可以处理所有这些,但事情并不清楚。 I'd personally use Noda Time (which shouldn't surprise anyone as it's my own library...) 我个人使用Noda Time (这不应该让任何人感到惊讶,因为它是我自己的库......)

LocalDate startDate = ...;
LocalDate endDate = ...;

long days = Period.Between(startDate, endDate, PeriodUnits.Days).Days;

Note that finding "today's date" requires knowing the appropriate time zone, too. 请注意,查找“今天的日期”也需要知道适当的时区。 ( DateTime.Now and DateTime.Today assume the system time zone where your code is running, but that may or may not be what you want.) DateTime.NowDateTime.Today假设您的代码正在运行的系统时区,但这可能是您想要的,也可能不是。)

You need TimeSpan 你需要TimeSpan

Timespan t = ReturnDateTime - DateTime.Now;

Then use 然后用

t.Days

for calculating how many days are left. 用于计算剩余的天数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM