Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 计算年、月、周和日_C#_.net_Date_Timespan - Fatal编程技术网

C# 计算年、月、周和日

C# 计算年、月、周和日,c#,.net,date,timespan,C#,.net,Date,Timespan,在我的应用程序中,用户输入两个日期。计划开始日期和计划结束日期。我们必须采用这些日期,并根据差异填充4个字段 因此,假设他选择2010年1月1日作为开始,2011年3月2日作为结束,我们需要以以下方式结束: 年份:1 月份:2 周数:0 第1天 这意味着总持续时间为1年2个月1天 有没有一个标准的方法可以做到这一点?或者我需要写一个有很多复杂逻辑的方法来解决它吗?我希望我会很幸运,并且会有一个日期差异类型的.Net课程 我想这就是你想要的,但它不适合几年或几个月,因为它们的长度不同 下面的例子来

在我的应用程序中,用户输入两个日期。计划开始日期和计划结束日期。我们必须采用这些日期,并根据差异填充4个字段

因此,假设他选择2010年1月1日作为开始,2011年3月2日作为结束,我们需要以以下方式结束:

年份:1 月份:2 周数:0 第1天

这意味着总持续时间为1年2个月1天

有没有一个标准的方法可以做到这一点?或者我需要写一个有很多复杂逻辑的方法来解决它吗?我希望我会很幸运,并且会有一个日期差异类型的.Net课程

我想这就是你想要的,但它不适合几年或几个月,因为它们的长度不同

下面的例子来自上面的链接

// Define two dates.
DateTime date1 = new DateTime(2010, 1, 1, 8, 0, 15);
DateTime date2 = new DateTime(2010, 8, 18, 13, 30, 30);
// Calculate the interval between the two dates.
TimeSpan interval = date2 - date1;
Console.WriteLine("{0} - {1} = {2}", date2, date1, interval.ToString());
// Display individual properties of the resulting TimeSpan object.
Console.WriteLine("   {0,-35} {1,20}", "Value of Days Component:", interval.Days);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Days:", interval.TotalDays);
Console.WriteLine("   {0,-35} {1,20}", "Value of Hours Component:", interval.Hours);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Hours:", interval.TotalHours);
Console.WriteLine("   {0,-35} {1,20}", "Value of Minutes Component:", interval.Minutes);
Console.WriteLine("   {0,-35} {1,20}", "Total Number of Minutes:", interval.TotalMinutes);
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Seconds Component:", interval.Seconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Seconds:", interval.TotalSeconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Value of Milliseconds Component:", interval.Milliseconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Total Number of Milliseconds:", interval.TotalMilliseconds);
Console.WriteLine("   {0,-35} {1,20:N0}", "Ticks:", interval.Ticks);
// the example displays the following output:
//       8/18/2010 1:30:30 PM - 1/1/2010 8:00:15 AM = 229.05:30:15
//          Value of Days Component:                             229
//          Total Number of Days:                   229.229340277778
//          Value of Hours Component:                              5
//          Total Number of Hours:                  5501.50416666667
//          Value of Minutes Component:                           30
//          Total Number of Minutes:                       330090.25
//          Value of Seconds Component:                           15
//          Total Number of Seconds:                      19,805,415
//          Value of Milliseconds Component:                       0
//          Total Number of Milliseconds:             19,805,415,000
//          Ticks:                               198,054,150,000,000

研究C#结构。它不会持续数月或数年,但会持续数天。这使事情变得更简单。

您可以使用免费库的DateDiff类:

// ----------------------------------------------------------------------
public void DateDiffSample()
{
  DateTime date1 = new DateTime( 2009, 11, 8, 7, 13, 59 );
  Console.WriteLine( "Date1: {0}", date1 );
  // > Date1: 08.11.2009 07:13:59
  DateTime date2 = new DateTime( 2011, 3, 20, 19, 55, 28 );
  Console.WriteLine( "Date2: {0}", date2 );
  // > Date2: 20.03.2011 19:55:28

  DateDiff dateDiff = new DateDiff( date1, date2 );

  // differences
  Console.WriteLine( "DateDiff.Years: {0}", dateDiff.Years );
  // > DateDiff.Years: 1
  Console.WriteLine( "DateDiff.Quarters: {0}", dateDiff.Quarters );
  // > DateDiff.Quarters: 5
  Console.WriteLine( "DateDiff.Months: {0}", dateDiff.Months );
  // > DateDiff.Months: 16
  Console.WriteLine( "DateDiff.Weeks: {0}", dateDiff.Weeks );
  // > DateDiff.Weeks: 70
  Console.WriteLine( "DateDiff.Days: {0}", dateDiff.Days );
  // > DateDiff.Days: 497
  Console.WriteLine( "DateDiff.Weekdays: {0}", dateDiff.Weekdays );
  // > DateDiff.Weekdays: 71
  Console.WriteLine( "DateDiff.Hours: {0}", dateDiff.Hours );
  // > DateDiff.Hours: 11940
  Console.WriteLine( "DateDiff.Minutes: {0}", dateDiff.Minutes );
  // > DateDiff.Minutes: 716441
  Console.WriteLine( "DateDiff.Seconds: {0}", dateDiff.Seconds );
  // > DateDiff.Seconds: 42986489

  // elapsed
  Console.WriteLine( "DateDiff.ElapsedYears: {0}", dateDiff.ElapsedYears );
  // > DateDiff.ElapsedYears: 1
  Console.WriteLine( "DateDiff.ElapsedMonths: {0}", dateDiff.ElapsedMonths );
  // > DateDiff.ElapsedMonths: 4
  Console.WriteLine( "DateDiff.ElapsedDays: {0}", dateDiff.ElapsedDays );
  // > DateDiff.ElapsedDays: 12
  Console.WriteLine( "DateDiff.ElapsedHours: {0}", dateDiff.ElapsedHours );
  // > DateDiff.ElapsedHours: 12
  Console.WriteLine( "DateDiff.ElapsedMinutes: {0}", dateDiff.ElapsedMinutes );
  // > DateDiff.ElapsedMinutes: 41
  Console.WriteLine( "DateDiff.ElapsedSeconds: {0}", dateDiff.ElapsedSeconds );
  // > DateDiff.ElapsedSeconds: 29
} // DateDiffSample

这是一个完整的方法,不包括周,但可以相对简单地添加。这是一个有点复杂的问题(在stackoverflow上以多种方式被问到,但在多种方式中回答得很差),但仍然无法回答。TimeSpan对象提供了我们所需的部分内容,但只在几天内起作用。我已经针对这种方法编写了大量测试,如果您发现了漏洞,请发表评论

这将做的是比较两个日期,得到年、月、日、小时和分钟。(例如,一些事件发生在1年、6个月、3天、4小时和7分钟前)

因为这个问题已经被问了很多次,并且试图得到回答,我不确定这是否会被注意到,但如果是这样的话,它应该会提供价值

    public static void TimeSpanToDateParts(DateTime d1, DateTime d2, out int years, out int months, out int days, out int hours, out int minutes)
    {
        if (d1 < d2)
        {
            var d3 = d2;
            d2 = d1;
            d1 = d3;
        }

        var span = d1 - d2;

        months = 12 * (d1.Year - d2.Year) + (d1.Month - d2.Month);

        //month may need to be decremented because the above calculates the ceiling of the months, not the floor.
        //to do so we increase d2 by the same number of months and compare.
        //(500ms fudge factor because datetimes are not precise enough to compare exactly)
        if (d1.CompareTo(d2.AddMonths(months).AddMilliseconds(-500)) <= 0)
        {
            --months;
        }

        years = months / 12;
        months -= years * 12;

        if (months == 0 && years == 0)
        {
            days = span.Days;
        }
        else
        {
            var md1 = new DateTime(d1.Year, d1.Month, d1.Day);
            // Fixed to use d2.Day instead of d1.Day
            var md2 = new DateTime(d2.Year, d2.Month, d2.Day);
            var mDays = (int) (md1 - md2).TotalDays;

            if (mDays > span.Days)
            {
                mDays = (int)(md1.AddMonths(-1) - md2).TotalDays;
            }

            days = span.Days - mDays;


        }
        hours = span.Hours;
        minutes = span.Minutes;
    }
public static void TimeSpanToDateParts(DateTime d1、DateTime d2、out int年、out int月、out int天、out int小时、out int分钟)
{
如果(d1
公共部分类Age1:System.Web.UI.Page
{
私人年资;
私人整数月;
私人国际日;
日期时间Cday;
日期时间B日;
受保护的无效页面加载(对象发送方、事件参数e)
{
txtCurrentDate.Enabled=false;
txtCurrentDate.Text=DateTime.Now.ToString(“g”);
Cday=Convert.ToDateTime(txtCurrentDate.Text);
}
受保护的无效按钮1\u单击(对象发送者,事件参数e)
{
Bday=Convert.ToDateTime(txtbirchdate.Text);
年龄计算(b天,c天);
txtbirchdate.Text=“”;
txtCurrentDate.Text=“”;
lblAge.Text=this.Years+“Years”+this.Months+“Months”+this.Days+“Days”;
}
私人Age1 AgeCaluclation(日期时间Bday、日期时间Cday)
{
如果((Cday.Year-Bday.Year)>0 |
(((Cday.Year-Bday.Year)=0)和
((b日.月=Bday.Day)
{
this.Years=Cday.Year-Bday.Year;
这个。月=0;
this.Days=Cday.Day-Bday.Day;
}
其他的
{
this.Years=(Cday.Year-1)-Bday.Year;
这个月=11个月;
this.Days=DateTime.DaysInMonth(Bday.Year,Bday.Month)-(Bday.Day-Cday.Day);
}
}
其他的
{
this.Years=(Cday.Year-1)-Bday.Year;
this.Months=Cday.Month+(11-Bday.Month)+Math.Abs(DaysRemain/DaysInBdayMonth);
this.Days=(DaysResMain%DaysInBdayMonth+DaysInBdayMonth)%DaysInBdayMonth;
}
}
其他的
{
抛出新ArgumentException(“生日日期必须早于当前日期”);
}
归还这个;
}
}

我也需要这个,但在我的情况下,没有周部分(所以只有年、月和日)。鉴于此,我做了如下:

DateTime startDate = DateTime.ParseExact (start, "dd/MM/yyyy",CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact (end, "dd/MM/yyyy",CultureInfo.InvariantCulture);
int days=0;
int months = 0;
int years = 0;
//calculate days
if (endDate.Day >= startDate.Day) {
    days = endDate.Day - startDate.Day;
} else {
    var tempDate = endDate.AddMonths (-1);
    int daysInMonth = DateTime.DaysInMonth (tempDate.Year, tempDate.Month);
    days = daysInMonth - (startDate.Day - endDate.Day);
    months--;
}
//calculate months
if (endDate.Month >= startDate.Month) {
    months+=endDate.Month - startDate.Month;
} else {
    months+= 12 - (startDate.Month - endDate.Month);
    years--;
}
//calculate years
years+=endDate.Year - startDate.Year;
Debug.WriteLine (string.Format("{0} years, {1} months, {2} days",years,months,days));
如果要更动态地显示此代码,还可以使用以下代码:

//build the string
var result = "";
if (years!=0){
    result = years == 1 ? years + " year" : years + " years";
}
if (months != 0) {
    if (result != "") {
        result += ", ";
    }
    result += months == 1 ? months + " month" : months + " months";
}
if (days != 0) {
    if (result != "") {
        result += ", ";
    }
    result += days == 1 ? days + " day" : days + " days";
}
Debug.WriteLine (result);

我创建这一个是为了返回两个日期之间的年、月和日差

public static Dictionary<string, int> TimeSpanToDateParts(DateTime fromDate,DateTime toDate)
        {
            int years;
            int months;
            int days;
            Dictionary<string, int> dateParts = new Dictionary<string, int>();
            if (toDate < fromDate)
            {
               return TimeSpanToDateParts(toDate,fromDate);
            }

            var span = toDate - fromDate;

            months = 12 * (toDate.Year - fromDate.Year) + (toDate.Month - fromDate.Month);

            if (toDate.CompareTo(fromDate.AddMonths(months).AddMilliseconds(-500)) <= 0)
            {
                --months;
            }

            years = months / 12;
            months -= years * 12;

            if (months == 0 && years == 0)
            {
                days = span.Days;
            }
            else
            {
                days = toDate.Day;
                if (fromDate.Day > toDate.Day)
                    days = days + (DateTime.DaysInMonth(toDate.Year, toDate.Month - 1) - fromDate.Day);
                else
                    days = days - fromDate.Day;
            }
            dateParts.Add("Years", years);
            dateParts.Add("Months", months);
            dateParts.Add("Days", days);

            return dateParts;
        }
    /// <summary>
    /// //Assume DateTime dt1 < DateTime dt2, print out difference between dt1 to dt2 in years, months, weeks and days
    /// </summary>
    /// <param name="dt1"></param>
    /// <param name="dt2"></param>
    static void DateDiff(DateTime dt1, DateTime dt2)
    {
        DateTime zeroTime = new DateTime(1, 1, 1);

        int leapDaysInBetween = CountLeapDays(dt1, dt2);

        TimeSpan span = dt2 - dt1;

        int years = (zeroTime + span).Year - 1;
        int months = (zeroTime + span).Month - 1;
        int days = (zeroTime + span).Day - (leapDaysInBetween % 2 == 1 ? 1 : 0);
        int weeks = days / 7;
        int remainingdays = days % 7;

        Console.WriteLine(String.Format("\nThe difference between date {0} and date {1} is: \n\t {2} year(s), {3} month(s), and {4} day(s).", dt1, dt2, years, months, days));
        Console.WriteLine(String.Format("\nThe difference between date {0} and date {1} is: \n\t {2} year(s), {3} month(s), {4} week(s) and {5} day(s).", dt1, dt2, years, months, weeks, remainingdays));
    }

    private static int CountLeapDays(DateTime dt1, DateTime dt2)
    {
        int leapDaysInBetween = 0;
        int year1 = dt1.Year, year2 = dt2.Year;
        DateTime dateValue;

        for (int i = year1; i <= year2; i++)
        {
            if (DateTime.TryParse("02/29/" + i.ToString(), out dateValue))
            {
                if (dateValue >= dt1 && dateValue <= dt2)
                    leapDaysInBetween++;
            }
        }

        return leapDaysInBetween;
    }
publicstaticdictionary TimeSpanToDateParts(DateTime fromDate,DateTime toDate)
{
整数年;
整数个月;
国际日;
Dictionary dateParts=新字典();
如果(toDateDateTime start_date = new DateTime(2010, 1, 1);
DateTime end_date = new DateTime(2011, 3, 2);

int diff_years = end_date.Year - start_date.Year;
int diff_months = end_date.Month - start_date.Month;

int total_months = 12 * diff_years + diff_months;
DateTime near_end_date = start_date.AddMonths(total_months);
int total_days = (int)end_date.Subtract(near_end_date).TotalDays;

int years = total_months / 12;
int months = total_months % 12;
int weeks = total_days / 7;
int days = total_days % 7;

Console.WriteLine($"Years: {years} Months: {months} Weeks: {weeks} Days: {days}");
    /// <summary>
    /// //Assume DateTime dt1 < DateTime dt2, print out difference between dt1 to dt2 in years, months, weeks and days
    /// </summary>
    /// <param name="dt1"></param>
    /// <param name="dt2"></param>
    static void DateDiff(DateTime dt1, DateTime dt2)
    {
        DateTime zeroTime = new DateTime(1, 1, 1);

        int leapDaysInBetween = CountLeapDays(dt1, dt2);

        TimeSpan span = dt2 - dt1;

        int years = (zeroTime + span).Year - 1;
        int months = (zeroTime + span).Month - 1;
        int days = (zeroTime + span).Day - (leapDaysInBetween % 2 == 1 ? 1 : 0);
        int weeks = days / 7;
        int remainingdays = days % 7;

        Console.WriteLine(String.Format("\nThe difference between date {0} and date {1} is: \n\t {2} year(s), {3} month(s), and {4} day(s).", dt1, dt2, years, months, days));
        Console.WriteLine(String.Format("\nThe difference between date {0} and date {1} is: \n\t {2} year(s), {3} month(s), {4} week(s) and {5} day(s).", dt1, dt2, years, months, weeks, remainingdays));
    }

    private static int CountLeapDays(DateTime dt1, DateTime dt2)
    {
        int leapDaysInBetween = 0;
        int year1 = dt1.Year, year2 = dt2.Year;
        DateTime dateValue;

        for (int i = year1; i <= year2; i++)
        {
            if (DateTime.TryParse("02/29/" + i.ToString(), out dateValue))
            {
                if (dateValue >= dt1 && dateValue <= dt2)
                    leapDaysInBetween++;
            }
        }

        return leapDaysInBetween;
    }
static void Main(string[] args)
{
    DateDiff(new DateTime(2010, 1, 1), new DateTime(2012, 2, 9));
    DateDiff(new DateTime(2010, 1, 1), new DateTime(2012, 4, 9));
    DateDiff(new DateTime(2010, 1, 1), new DateTime(2020, 2, 9));
    DateDiff(new DateTime(2010, 1, 1), new DateTime(2020, 4, 9));
    DateDiff(new DateTime(2020, 2, 29), new DateTime(2021, 2, 28));
    DateDiff(new DateTime(2019, 2, 28), new DateTime(2021, 2, 28));
}
        DateTime beforeDate = topic.lastActive.ToLocalTime();
        DateTime futureDate = DateTime.Now.ToLocalTime();

        int minutes = 0;
        int hours = 0;
        int days = 0;
        int weeks = 0;
        int months = 0;
        int years = 0;

        Dictionary<int, int> dictMonths = new Dictionary<int, int> { };
        dictMonths.Add(1, 31);
        if (DateTime.IsLeapYear(futureDate.Year))
            dictMonths.Add(2, 29);
        else
            dictMonths.Add(2, 28);
        dictMonths.Add(3, 31);
        dictMonths.Add(4, 30);
        dictMonths.Add(5, 31);
        dictMonths.Add(6, 30);
        dictMonths.Add(7, 31);
        dictMonths.Add(8, 31);
        dictMonths.Add(9, 30);
        dictMonths.Add(10, 31);
        dictMonths.Add(11, 30);
        dictMonths.Add(12, 31);

        //Time difference between dates
        TimeSpan span = futureDate - beforeDate;
        hours = span.Hours;
        minutes = span.Minutes;

        //Days total
        days = span.Days;
        //Find how many years
        DateTime zeroTime = new DateTime(1, 1, 1);

        // Because we start at year 1 for the Gregorian
        // calendar, we must subtract a year here.
        years = (zeroTime + span).Year - 1;
        //find difference of days of years already found
        int startYear = futureDate.Year - years;
        for (int i = 0; i < years; i++)
        {
            if (DateTime.IsLeapYear(startYear))
                days -= 366;
            else
                days -= 365;

            startYear++;
        }
        //Find months by multiplying months in year by difference of datetime years then add difference of current year months
        months = 12 * (futureDate.Year - beforeDate.Year) + (futureDate.Month - beforeDate.Month);
        //month may need to be decremented because the above calculates the ceiling of the months, not the floor.
        //to do so we increase before by the same number of months and compare.
        //(500ms fudge factor because datetimes are not precise enough to compare exactly)
        if (futureDate.CompareTo(beforeDate.AddMonths(months).AddMilliseconds(-500)) <= 0)
        {
            --months;
        }
        //subtract months from how many years we have already accumulated
        months -= (12 * years);
        //find how many days by compared to our month dictionary
        int startMonth = beforeDate.Month;
        for (int i = 0; i < months; i++)
        {
            //check if faulty leap year
            if (startMonth == 2 && (months - 1 > 10))
                days -= 28;
            else
                days -= dictMonths[startMonth];
            startMonth++;
            if (startMonth > 12)
            {
                startMonth = 1;
            }
        }
        //Find if any weeks are within our now total days
        weeks = days / 7;
        if (weeks > 0)
        {
            //remainder is days left
            days = days % 7;
        }

        Console.WriteLine(years + " " + months + " " + weeks + " " + days + " " + span.Hours + " " + span.Minutes);

        if (years > 0)
        {
            if (years > 1 && months > 1)
                return $"Latest Reply: {years} years, {months} months ago.";
            else if (years > 1 && months == 0)
                return $"Latest Reply: {years} years ago.";
            else if (years == 1 && months == 0)
                return $"Latest Reply: {years} year ago.";
            else if (years > 1)
                return $"Latest Reply: {years} years, {months} month ago.";
            else if (months > 1)
                return $"Latest Reply: {years} year, {months} months ago.";
            else
                return $"Latest Reply: {years} year, {months} month ago.";
        }
        else if (months > 0)
        {
            if (months > 1 && weeks > 1)
                return $"Latest Reply: {months} months, {weeks} weeks ago.";
            else if (months > 1 && weeks == 0)
                return $"Latest Reply: {months} months ago.";
            else if (months == 1 && weeks == 0)
                return $"Latest Reply: {months} month ago.";
            else if (months > 1)
                return $"Latest Reply: {months} months, {weeks} week ago.";
            else if (weeks > 1)
                return $"Latest Reply: {months} month, {weeks} weeks ago.";
            else
                return $"Latest Reply: {months} month, {weeks} week ago.";
        }
        else if (weeks > 0)
        {
            if (weeks > 1 && days > 1)
                return $"Latest Reply: {weeks} weeks, {days} days ago.";
            else if (weeks > 1 && days == 0)
                return $"Latest Reply: {weeks} weeks ago.";
            else if (weeks == 1 && days == 0)
                return $"Latest Reply: {weeks} week ago.";
            else if (weeks > 1)
                return $"Latest Reply: {weeks} weeks, {days} day ago.";
            else if (days > 1)
                return $"Latest Reply: {weeks} week, {days} days ago.";
            else
                return $"Latest Reply: {weeks} week, {days} day ago.";
        }
        else if (days > 0)
        {
            if (days > 1 && hours > 1)
                return $"Latest Reply: {days} days, {hours} hours ago.";
            else if (days > 1 && hours == 0)
                return $"Latest Reply: {days} days ago.";
            else if (days == 1 && hours == 0)
                return $"Latest Reply: {days} day ago.";
            else if (days > 1)
                return $"Latest Reply: {days} days, {hours} hour ago.";
            else if (hours > 1)
                return $"Latest Reply: {days} day, {hours} hours ago.";
            else
                return $"Latest Reply: {days} day, {hours} hour ago.";
        }
        else if (hours > 0)
        {
            if (hours > 1 && minutes > 1)
                return $"Latest Reply: {hours} hours, {minutes} minutes ago.";
            else if (hours > 1 && minutes == 0)
                return $"Latest Reply: {hours} hours ago.";
            else if (hours == 1 && minutes == 0)
                return $"Latest Reply: {hours} hour ago.";
            else if (hours > 1)
                return $"Latest Reply: {hours} hours, {minutes} minute ago.";
            else if (minutes > 1)
                return $"Latest Reply: {hours} hour, {minutes} minutes ago.";
            else
                return $"Latest Reply: {hours} hour, {minutes} minute ago.";
        }
        else if (minutes > 0)
        {
            if (minutes > 1)
                return $"Latest Reply: {minutes} minutes ago.";
            else
                return $"Latest Reply: {minutes} minute ago.";
        }
        else
        {
            return $"Latest Reply: Just now.";
        }