Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.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#_Date - Fatal编程技术网

C# 生日年龄计算,也可用于月数和天数

C# 生日年龄计算,也可用于月数和天数,c#,date,C#,Date,您好,因此我实施了此解决方案,以通过生日日期输入获得用户的生日: 这很好用,但是我需要为小于一岁的婴儿解释生日。如果从b日期到当前日期之间的间隔少于365天,它将只给我一个0的年龄 我的想法是这样的: public string calculateAge(DateTime birthDate, DateTime now) { //BDay is in different year (age > 1) int age = no

您好,因此我实施了此解决方案,以通过生日日期输入获得用户的生日:

这很好用,但是我需要为小于一岁的婴儿解释生日。如果从b日期到当前日期之间的间隔少于365天,它将只给我一个0的年龄

我的想法是这样的:

public string calculateAge(DateTime birthDate, DateTime now)
        {
            //BDay is in different year (age > 1)
            int age = now.Year - birthDate.Year;
            if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;

            if (age == 0)
            {
                //Bday is in same year
                age = now.Month - birthDate.Month;
                if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;

                return age.ToString() + " months";
            }
            if (age == 0)
            {
                //Bday is in the same month
                age = now.Day - birthDate.Day;
                if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;

                return age.ToString() + " days";
            }
            return age.ToString();
        }
您可以看到,由于当前的设置方式,当bday-month小于当前月份时,可能会产生一些负数


我也看到了无法进入days循环的错误,但我认为这是一个没有意义的问题。让我知道,如果你有任何见解,我可以做什么,以获得理想的结果。如果你还需要更多的信息,比如考试B日。谢谢

您可以使用我发现的这个函数:

/// <summary>
/// Converts a timespan value to a string representation.
/// </summary>
/// <param name="time_span">the amount of time to convert to words</param>
/// <param name="whole_seconds">round up the seconds</param>
/// <returns>4 minutes, 58 seconds, etc</returns>
/// <remarks>If it can't convert to a string, it returns "Calculating time remaining..."</remarks>
public string TimespanToWords(TimeSpan time_span, bool whole_seconds = true)
{
    TimeSpan span;
    string str2 = "";
    if (time_span.Days > 0)
    {
        str2 = str2 + ", " + time_span.Days.ToString() + " days";
        span = new TimeSpan(time_span.Days, 0, 0, 0);
        time_span = time_span.Subtract(span);
    }
    if (time_span.Hours > 0)
    {
        str2 = str2 + ", " + time_span.Hours.ToString() + " hours";
        span = new TimeSpan(0, time_span.Hours, 0, 0);
        time_span = time_span.Subtract(span);
    }
    if (time_span.Minutes > 0)
    {
        str2 = str2 + ", " + time_span.Minutes.ToString() + " minutes";
        span = new TimeSpan(0, 0, time_span.Minutes, 0);
        time_span = time_span.Subtract(span);
    }
    if (whole_seconds)
    {
        if (time_span.Seconds > 0)
        {
            str2 = str2 + ", " + time_span.Seconds.ToString() + " seconds";
        }
    }
    else
    {
        str2 = str2 + ", " + time_span.TotalSeconds.ToString() + " seconds";
    }
    if (str2.Length > 0)
    {
        str2 = str2.Substring(2);
    }
    if (string.IsNullOrEmpty(str2))
    {
        return "Calculating time remaining...";
    }
    return str2;
}

您可以使用我发现的这个函数:

/// <summary>
/// Converts a timespan value to a string representation.
/// </summary>
/// <param name="time_span">the amount of time to convert to words</param>
/// <param name="whole_seconds">round up the seconds</param>
/// <returns>4 minutes, 58 seconds, etc</returns>
/// <remarks>If it can't convert to a string, it returns "Calculating time remaining..."</remarks>
public string TimespanToWords(TimeSpan time_span, bool whole_seconds = true)
{
    TimeSpan span;
    string str2 = "";
    if (time_span.Days > 0)
    {
        str2 = str2 + ", " + time_span.Days.ToString() + " days";
        span = new TimeSpan(time_span.Days, 0, 0, 0);
        time_span = time_span.Subtract(span);
    }
    if (time_span.Hours > 0)
    {
        str2 = str2 + ", " + time_span.Hours.ToString() + " hours";
        span = new TimeSpan(0, time_span.Hours, 0, 0);
        time_span = time_span.Subtract(span);
    }
    if (time_span.Minutes > 0)
    {
        str2 = str2 + ", " + time_span.Minutes.ToString() + " minutes";
        span = new TimeSpan(0, 0, time_span.Minutes, 0);
        time_span = time_span.Subtract(span);
    }
    if (whole_seconds)
    {
        if (time_span.Seconds > 0)
        {
            str2 = str2 + ", " + time_span.Seconds.ToString() + " seconds";
        }
    }
    else
    {
        str2 = str2 + ", " + time_span.TotalSeconds.ToString() + " seconds";
    }
    if (str2.Length > 0)
    {
        str2 = str2.Substring(2);
    }
    if (string.IsNullOrEmpty(str2))
    {
        return "Calculating time remaining...";
    }
    return str2;
}

实际上,我们的框架中有一个日期跨度结构,用于进行类似的计算。。。与您所追求的目标相关的关键在于,对于定义的开始和结束日期时间变量,它的属性如下:

    public int WholeMonths
    {
        get
        {
            var startInEndsYear = Start.AddYears(End.Year - Start.Year);

            // Are within a month of each other if EITHER:
            // 1. Month is the same
            // 2. Month period is within 1 
            //    AND
            //    The difference between days of the year is less than the number of days in the start's month
            var sameMonth = End.Month == startInEndsYear.Month || (End.Month - 1 == Start.Month && (End.DayOfYear - startInEndsYear.DayOfYear) / (double)DateTime.DaysInMonth(startInEndsYear.Year, startInEndsYear.Month) < 1.0d );
            var sameMonthAndDay = sameMonth && End.Day == Start.Day;

            var res = (End.Year - Start.Year) * 12;
            if (sameMonth && !sameMonthAndDay)
            {
                res -= (startInEndsYear > End) ? 1 : 0;
            }
            else if (sameMonthAndDay)
            {
                res -= (End.TimeOfDay < Start.TimeOfDay ? 1 : 0);
            }
            else
            {
                res -= Start.Month;
                res += End.Month;
            }
            return res;
        }
    }
我将把它留作进一步的练习,让您根据这些属性转换为单词

编辑:以下是天数的计算:

    public TimeSpan PartDays
    {
        get
        {
            var startInEndsMonth = Start.AddMonths(WholeMonths);
            return End.Subtract(startInEndsMonth);
        }
    }

实际上,我们的框架中有一个日期跨度结构,用于进行类似的计算。。。与您所追求的目标相关的关键在于,对于定义的开始和结束日期时间变量,它的属性如下:

    public int WholeMonths
    {
        get
        {
            var startInEndsYear = Start.AddYears(End.Year - Start.Year);

            // Are within a month of each other if EITHER:
            // 1. Month is the same
            // 2. Month period is within 1 
            //    AND
            //    The difference between days of the year is less than the number of days in the start's month
            var sameMonth = End.Month == startInEndsYear.Month || (End.Month - 1 == Start.Month && (End.DayOfYear - startInEndsYear.DayOfYear) / (double)DateTime.DaysInMonth(startInEndsYear.Year, startInEndsYear.Month) < 1.0d );
            var sameMonthAndDay = sameMonth && End.Day == Start.Day;

            var res = (End.Year - Start.Year) * 12;
            if (sameMonth && !sameMonthAndDay)
            {
                res -= (startInEndsYear > End) ? 1 : 0;
            }
            else if (sameMonthAndDay)
            {
                res -= (End.TimeOfDay < Start.TimeOfDay ? 1 : 0);
            }
            else
            {
                res -= Start.Month;
                res += End.Month;
            }
            return res;
        }
    }
我将把它留作进一步的练习,让您根据这些属性转换为单词

编辑:以下是天数的计算:

    public TimeSpan PartDays
    {
        get
        {
            var startInEndsMonth = Start.AddMonths(WholeMonths);
            return End.Subtract(startInEndsMonth);
        }
    }

这是一种计算年龄的方法,就像西方文化中的正常人计算年龄一样。不同的文化和日历以不同的方式计算年龄。例如,一个新生婴儿出生当天的年龄是1岁,而他的年龄在中国历法中随后的每个农历新年都会增加。因此,如果一个孩子在农历新年前一个月出生,他将在该月满1岁,然后在出生后一个月满2岁

此算法不适用于BCE日期或从儒略历到公历的过渡日期。无论如何,这是一个冒险的命题,不管你如何划分它,因为不同的地点,甚至在同一个国家内,在不同的时间切换:例如,俄罗斯直到布尔什维克革命后才切换到公历

因此,除非您有开始日期的区域设置和结束日期的区域设置,否则无法准确计算跨越朱利安/格里高利分的时间跨度

算法是:

查找参考日期,即当前日期当天或之前的最近一个月的生日

如果当月的当前日期早于实际出生日期,则使用前一个月。如果实际出生日期晚于当月最后一天,则在当月最后一天设定上限

例如,如果当前日期为2012年3月7日,实际生日为“1990年3月31日”,则参考日期为2012年2月29日

计算您的参考日期和出生日期之间的差异(以年和月为单位)。这很容易,因为在西方历法中,年的月数是一致的。可以使用整数除法:

int totalMonths=12*年末+月末-12*开始月+开始月; 整数年=总月数/12; 整月=总月数%12

或者,如果需要的话,你可以减法并携带

int years  = endYear  - startYear  ;
int months = endMonth - startMonth ;

if ( months < 0 )
{
  months += 12 ;
  years  -=  1 ;
}
无论哪种情况,结果都应该相同

days组件是从参考日期到当前日期的天数

使用此算法,一个在出生当天为0天

这是我的密码:

static class HumanAgeFactory
{

  public static HumanAge ComputeAge( this DateTime dob )
  {
    return dob.ComputeAgeAsOf( DateTime.Now ) ;
  }

  public static HumanAge ComputeAgeAsOf( this DateTime dob , DateTime now )
  {
    dob = dob.Date ; // toss the time component
    now = now.Date ; // toss the time component

    if ( dob > now ) throw new ArgumentOutOfRangeException( "dob" , "'now' must be on or after 'dob'" ) ;

    DateTime mostRecentBirthDay = MostRecentNthDayOfTheMonthOnOrBefore( dob.Day , now ) ;
    int      years              = mostRecentBirthDay.Year  - dob.Year          ;
    int      months             = mostRecentBirthDay.Month - dob.Month         ;
    int      days               = (int) ( now - mostRecentBirthDay ).TotalDays ;

    if ( months < 0 )
    {
      months += 12 ;
      years  -=  1 ;
    }

    if ( days   < 0 ) throw new InvalidOperationException() ;
    if ( months < 0 ) throw new InvalidOperationException() ;
    if ( years  < 0 ) throw new InvalidOperationException() ;

    HumanAge instance = new HumanAge( years , months , days ) ;
    return instance ;
  }

  private static DateTime MostRecentNthDayOfTheMonthOnOrBefore( int nthDay , DateTime now )
  {
    if ( nthDay < 1 ) throw new ArgumentOutOfRangeException( "dayOfBirth" ) ;

    int year  = now.Year  ;
    int month = now.Month ;

    if ( nthDay > now.Day )
    {
      --month ;
      if ( month < 1 )
      {
        month += 12 ;
        year  -=  1 ;
      }
    }

    int daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth( year , month ) ;
    int day         = ( nthDay > daysInMonth ? daysInMonth : nthDay ) ;

    DateTime instance = new DateTime( year , month , day ) ;
    return instance ;
  }

}

public class HumanAge
{
  public int Years  { get ; private set ; }
  public int Months { get ; private set ; }
  public int Days   { get ; private set ; }

  public override string ToString()
  {
    string instance = string.Format( "{0} {1} , {2} {3} , {4} {5}" ,
      Years  , Years  == 1 ? "year"  : "years"  ,
      Months , Months == 1 ? "month" : "months" ,
      Days   , Days   == 1 ? "day"   : "days"
      ) ;
    return instance ;
  }

  public HumanAge( int years , int months , int days )
  {
    if ( years  < 0                ) throw new ArgumentOutOfRangeException( "years"  ) ;
    if ( months < 0 || months > 12 ) throw new ArgumentOutOfRangeException( "months" ) ;
    if ( days   < 0 || days   > 31 ) throw new ArgumentOutOfRangeException( "days"   ) ;

    this.Years  = years  ;
    this.Months = months ;
    this.Days   = days   ;

    return ;
  }

}

这是一种计算年龄的方法,就像西方文化中的正常人计算年龄一样。不同的文化和日历以不同的方式计算年龄。例如,一个新生婴儿出生当天的年龄是1岁,而他的年龄在中国历法中随后的每个农历新年都会增加。因此,如果一个孩子在农历新年前一个月出生,他将在该月满1岁,然后在出生后一个月满2岁

此算法不适用于BCE日期或从儒略历到公历的过渡日期。无论如何,这是一个冒险的命题,不管你如何划分它,因为不同的地点,甚至在同一个国家内,在不同的时间切换:例如,俄罗斯直到布尔什维克革命后才切换到公历

因此,除非您有开始日期的区域设置和结束日期的区域设置,否则无法准确计算跨越朱利安/格里高利分的时间跨度

算法是:

查找参考日期 ,当前日期当天或之前的最近一个月生日

如果当月的当前日期早于实际出生日期,则使用前一个月。如果实际出生日期晚于当月最后一天,则在当月最后一天设定上限

例如,如果当前日期为2012年3月7日,实际生日为“1990年3月31日”,则参考日期为2012年2月29日

计算您的参考日期和出生日期之间的差异(以年和月为单位)。这很容易,因为在西方历法中,年的月数是一致的。可以使用整数除法:

int totalMonths=12*年末+月末-12*开始月+开始月; 整数年=总月数/12; 整月=总月数%12

或者,如果需要的话,你可以减法并携带

int years  = endYear  - startYear  ;
int months = endMonth - startMonth ;

if ( months < 0 )
{
  months += 12 ;
  years  -=  1 ;
}
无论哪种情况,结果都应该相同

days组件是从参考日期到当前日期的天数

使用此算法,一个在出生当天为0天

这是我的密码:

static class HumanAgeFactory
{

  public static HumanAge ComputeAge( this DateTime dob )
  {
    return dob.ComputeAgeAsOf( DateTime.Now ) ;
  }

  public static HumanAge ComputeAgeAsOf( this DateTime dob , DateTime now )
  {
    dob = dob.Date ; // toss the time component
    now = now.Date ; // toss the time component

    if ( dob > now ) throw new ArgumentOutOfRangeException( "dob" , "'now' must be on or after 'dob'" ) ;

    DateTime mostRecentBirthDay = MostRecentNthDayOfTheMonthOnOrBefore( dob.Day , now ) ;
    int      years              = mostRecentBirthDay.Year  - dob.Year          ;
    int      months             = mostRecentBirthDay.Month - dob.Month         ;
    int      days               = (int) ( now - mostRecentBirthDay ).TotalDays ;

    if ( months < 0 )
    {
      months += 12 ;
      years  -=  1 ;
    }

    if ( days   < 0 ) throw new InvalidOperationException() ;
    if ( months < 0 ) throw new InvalidOperationException() ;
    if ( years  < 0 ) throw new InvalidOperationException() ;

    HumanAge instance = new HumanAge( years , months , days ) ;
    return instance ;
  }

  private static DateTime MostRecentNthDayOfTheMonthOnOrBefore( int nthDay , DateTime now )
  {
    if ( nthDay < 1 ) throw new ArgumentOutOfRangeException( "dayOfBirth" ) ;

    int year  = now.Year  ;
    int month = now.Month ;

    if ( nthDay > now.Day )
    {
      --month ;
      if ( month < 1 )
      {
        month += 12 ;
        year  -=  1 ;
      }
    }

    int daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth( year , month ) ;
    int day         = ( nthDay > daysInMonth ? daysInMonth : nthDay ) ;

    DateTime instance = new DateTime( year , month , day ) ;
    return instance ;
  }

}

public class HumanAge
{
  public int Years  { get ; private set ; }
  public int Months { get ; private set ; }
  public int Days   { get ; private set ; }

  public override string ToString()
  {
    string instance = string.Format( "{0} {1} , {2} {3} , {4} {5}" ,
      Years  , Years  == 1 ? "year"  : "years"  ,
      Months , Months == 1 ? "month" : "months" ,
      Days   , Days   == 1 ? "day"   : "days"
      ) ;
    return instance ;
  }

  public HumanAge( int years , int months , int days )
  {
    if ( years  < 0                ) throw new ArgumentOutOfRangeException( "years"  ) ;
    if ( months < 0 || months > 12 ) throw new ArgumentOutOfRangeException( "months" ) ;
    if ( days   < 0 || days   > 31 ) throw new ArgumentOutOfRangeException( "days"   ) ;

    this.Years  = years  ;
    this.Months = months ;
    this.Days   = days   ;

    return ;
  }

}
您可以使用DateDiff类:

您可以使用DateDiff类:


以上不考虑天数。但无论如何,我会把它留给后人……上面没有考虑到时间。但无论如何,我会把它留给子孙后代……大家好,欢迎来到Stack Overflow。您可以通过说明它的作用、它如何解决问题来改进您的答案,也许还可以列出与此处发布的其他解决方案相比的好处。要改进它,您可以单击答案下的编辑按钮。您好,欢迎来到Stack Overflow。您可以通过说明它的作用、它如何解决问题来改进您的答案,也许还可以列出与此处发布的其他解决方案相比的好处。要改进它,您可以单击答案下的编辑按钮。
    int[] getAge(DateTime dt)
    {
        DateTime today = DateTime.Now;
        int years = 0;
        int days = 0;
        int months = 0;
        int[] age = new int[3];
        while (dt.Year != today.Year || dt.Month != today.Month || dt.Day != today.Day)
        {
            if (dt.AddYears(1).CompareTo(today) <= 0)
            {
                years++;
                dt = dt.AddYears(1);
            }
            else
            {
                if (dt.AddMonths(1).CompareTo(today) <= 0)
                {
                    months++;
                    dt = dt.AddMonths(1);
                }
                else
                {
                    if (dt.AddDays(1).CompareTo(today) <= 0)
                    {
                        days++;
                        dt = dt.AddDays(1);
                    }
                    else
                    {
                        dt = today;
                    }
                }

            }
        }
        age[0] = years;
        age[1] = months;
        age[2] = days;
        return age;
    }
// ----------------------------------------------------------------------
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 );

  // 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
} // DateDiffSample