C# - 将'days old'转换为出生日期? [英] C# - convert 'days old' to date of birth?

查看:114
本文介绍了C# - 将'days old'转换为出生日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我需要将某人的天数(例如3岁= 1,095天)转换为出生日期回答即dd / MM / yyyy。我已经尝试了很多不同的方法来做到这一点,但无济于事(例如) - 例如使用数学公式,但它有点复杂,特别是考虑如何将其实现到C#(至少对于初学者)。



以下方框中的内容是我迄今为止尝试过的众多方法之一。我知道这是错的,但这是我的许多尝试之一。什么是最简单的方式(假设1年是365天,如果计算机没有自己的自动计算以包含闰年)?



最后,如果我要包括闰年,那么调整是否只需要考虑1年= 365.25年?或者会有更复杂的事情吗?



亲切的问候。



我有什么试过:



Hi,

I need to convert how many 'days Old' someone is (e.g. 3 years old = 1,095 days old) to a 'date of birth' answer i.e. dd/MM/yyyy. I have tried many different ways how to do this, but to no avail (yet) - e.g. using a mathematical formula but it gets a bit complicated, especially when considering how to implement that into C# (for a beginner, at least).

What is in the box below is one of the many ways I have tried thus far. I know it's wrong but it's one of many of my attempts. What is the simplest way to go about this (assuming 1 year is 365 days, if the computer doesn't have it's own automated calculation to include leap years)?

Finally, if I am to include leap years, would the adjustment to simply be to take into consideration that 1 year = 365.25 years? Or would there be more complexity to this?

Kind regards.

What I have tried:

public static string GetBirthDate(int daysOld)
{
    var dateToday = Convert.ToInt32(DateTime.Now);

    var calc = (dateToday - 365.25 * daysOld);

    return Convert.ToString(calc);
}

推荐答案

如果我这样做,我会这样做:
If I were doing something like this, I would do it like this:
public static DateTime(int days)
{
  return new DateTime.Now.Subtract(TimeSpan.FromDays(days));
}


int daysOld = 1095;
DateTime dob = DateTime.Now.AddDays(daysOld * -1);


public static string GetBirthDate(int daysOld)
{
    // DateTime.Now.AddDays(-daysOld).To... has many format options
    // beware AddDays: daysOld conversion to type double

    return DateTime.Now.AddDays(-daysOld).ToString("dd'/'MM'/'yyyy")
}


这篇关于C# - 将'days old'转换为出生日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆