gpt4 book ai didi

c# - 生日年龄计算,也有月数和天数

转载 作者:太空宇宙 更新时间:2023-11-03 19:24:46 24 4
gpt4 key购买 nike

你好,我已经实现了这个解决方案来从输入的生日日期获取用户的生日: Calculate age in C#

这很好用,但我确实需要为不到一年的年龄(婴儿、婴儿)解释生日。如果 bdate 和当前日期之间的时间少于 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();
}

但是我的一些测试 Bdays 给我这个:

(Today's date: 3/6/2012)
Bday1 = 3/5/2012
Age result = -1
Expected result = 1 day

Bday2 = 3/1/2012
Age result = 0 months
Expected result = 5 days

Bday3 = 1/1/2012
Age result = 2 months
Expected result = 2 months (this is fine)

Bday4 = 3/7/2011
Age result = -1 months
Expected result = 11 months

Bday5 = 3/1/2011
Age result = 1
Expected result = 1 (this is fine)

您可以看到,由于当前的设置方式,问题源于当 bday 月份小于当前月份时,可能会产生一些负数。

我还看到有关无法进入“天数”循环的错误,但我认为现在这是一个有争议的问题。如果您对我可以做些什么来获得预期结果有任何见解,请告诉我。另外,如果您也需要更多信息,例如测试生日。谢谢!

最佳答案

您可以使用 Time Period Library for .NETDateDiff 类:

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

关于c# - 生日年龄计算,也有月数和天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com