【问题标题】:How to get DateOfBirth using age in c#?如何在 c# 中使用年龄获取 DateOfBirth?
【发布时间】:2018-10-17 03:15:03
【问题描述】:

我有用户年龄、月份和日期,例如 18 年 2 个月和 5 天。我需要使用这些参数返回用户DateOfBirth。如何从年月日中找到用户DateOfBirth

【问题讨论】:

  • 如果您能提供minimal reproducible example,那就太好了。
  • 如果某人出生于 2004 年 2 月 29 日,他们认为自己在 2005 年 2 月 28 日时多大(因为这会影响答案)?
  • 这是一道编程题还是一道数学题?仔细想想,如果这是关于如何在数学上解决这个问题,并且在你知道你可以很容易地在代码中实现它之后。
  • DateTime dt = new DateTime(1990, 12, 01, 0, 0, 0); 最后三个零是时间。以上将给12/1/1990 12:00:00 AM
  • @Flater,我正在研究医院账单管理解决方案,操作员喜欢在年份中插入年龄。月份和日期,而不是出生日期。

标签: c# .net datetime calc


【解决方案1】:

我找到了一个解决方案,它对我有用。

 public static DateTime GetDateOfBirth(int year, int month, int day)
    {
        var today = DateTime.Today;
        int currentYear = today.Year;
        int currentDay = today.Day;
        int currentMonth = today.Month;

        if (day >= currentDay)
        {
            currentMonth--;
            currentDay += DateTime.DaysInMonth(currentYear, currentMonth);
        }

        if (month >= currentMonth)
        {
            currentMonth += 12;
            currentYear--;
        }

        return new DateTime(currentYear - year, currentMonth - month, currentDay - day);
    }

【讨论】:

    【解决方案2】:

    您始终可以使用带负数的 AddDays/Months/Years 从日期中实际减去 Days/Months/Years。

    DateTime now = DateTime.Now;
    
    Console.WriteLine("Today's Date:" + now.ToString());
    
    int years = 18;
    int months = 2;
    int days = 5;
    now = now.AddYears((-1) * years);
    now = now.AddMonths((-1) * months);
    now = now.AddDays((-1) * days);
    
    Console.WriteLine("Date Of Birth:" + now.ToString());
    
    return now;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多