簡體   English   中英

更改日期數

[英]change a number of days to date

我該如何使用C#中的DateTime類將天數更改為(年,月和日),實際上我想計算生日的確切出生日期。 年?月..? 秒。

我的代碼:

DateTime a = new DateTime(1993, 6, 10, 0, 0, 0);
            DateTime now = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour
                ,DateTime.Now.Minute,DateTime.Now.Second);
            TimeSpan b = now - a;
            int c = b.Days;

您可以使用NodaTime

var period = NodaTime.Period.Between(
                new NodaTime.LocalDateTime(1993, 6, 10, 0, 0), 
                NodaTime.LocalDateTime.FromDateTime(DateTime.Now) );

Console.WriteLine("{0} {1} {2} {3} {4}",period.Years,period.Months,period.Days,
                                        period.Hours,period.Minutes);

我沒有看到簡單的功能。 即沒有辦法用一個簡單的DateTime函數來做到這一點。 但是,如果我將其放入代碼中,它將看起來像這樣:

DateTime birthday = new DateTime(1993, 6, 10);
DateTime current;
DateTime nowComparison = DateTime.Now;
int years = nowComparison.Year - birthday.Year;
if (nowComparison < birthday.AddYears(years))
    years -= 1;
current = birthday.AddYears(years); // current is less than a year ago.

int months;
if(current.Year != nowComparison.Year)
{
    months = nowComparison.Month + (12 - current.Month);
}
else
{
    months = nowComparison.Month - current.Month;
}
if (nowComparison < current.AddMonths(months))
    months -= 1;
current = current.AddMonths(months); // current is less than a month ago.

int days = nowComparison.Subtract(current).Days;
current = current.AddDays(days); // current is less than a day ago.

int hours = nowComparison.Subtract(current).Hours;
current = current.AddHours(hours); // current is less than an hour ago.

int minutes = nowComparison.Subtract(current).Minutes;
current = current.AddMinutes(minutes); // current is less than a minute ago.

int seconds = nowComparison.Subtract(current).Seconds;
current = current.AddSeconds(seconds); // current is less than a second ago.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM