C #을 사용한 연도의 날짜 차이
이 질문에 이미 답변이 있습니다.
연도의 두 날짜 간의 날짜 차이를 어떻게 계산할 수 있습니까?
예 : (Datetime.Now.Today() - 11/03/2007)
년.
정확히 1 년 간격의 날짜로 제대로 작동하는 구현을 작성했습니다.
그러나 다른 알고리즘과 달리 부정적인 시간 범위를 정상적으로 처리하지 않습니다. 또한 자체 날짜 산술을 사용하지 않고 대신 표준 라이브러리에 의존합니다.
따라서 더 이상 고민하지 않고 코드는 다음과 같습니다.
DateTime zeroTime = new DateTime(1, 1, 1);
DateTime a = new DateTime(2007, 1, 1);
DateTime b = new DateTime(2008, 1, 1);
TimeSpan span = b - a;
// Because we start at year 1 for the Gregorian
// calendar, we must subtract a year here.
int years = (zeroTime + span).Year - 1;
// 1, where my other algorithm resulted in 0.
Console.WriteLine("Yrs elapsed: " + years);
사용하다:
int Years(DateTime start, DateTime end)
{
return (end.Year - start.Year - 1) +
(((end.Month > start.Month) ||
((end.Month == start.Month) && (end.Day >= start.Day))) ? 1 : 0);
}
두 날짜 (시작일과 종료일)의 차이가 2 년 이상인지 확인하기 위해 검사 코드를 작성해야했습니다.
위의 팁 덕분에 다음과 같이 완료되었습니다.
DateTime StartDate = Convert.ToDateTime("01/01/2012");
DateTime EndDate = Convert.ToDateTime("01/01/2014");
DateTime TwoYears = StartDate.AddYears(2);
if EndDate > TwoYears .....
사소한 이유로 누군가의 나이를 알기 위해 필요하다면 Timespan은 괜찮지 만 재정적, 과학적 또는 법적 목적을 위해 연금, 장기 예금 또는 다른 것을 계산해야하는 경우 Timespan이 충분히 정확하지 않을 것입니다. 매년 동일한 일 수, 동일한 시간 및 동일한 초가 있다고 가정합니다.
실제로 몇 년의 길이는 다양합니다 (이 답변의 범위를 벗어난 여러 가지 이유로). Timespan의 한계를 극복하기 위해 Excel이 수행하는 작업을 모방 할 수 있습니다.
public int GetDifferenceInYears(DateTime startDate, DateTime endDate)
{
//Excel documentation says "COMPLETE calendar years in between dates"
int years = endDate.Year - startDate.Year;
if (startDate.Month == endDate.Month &&// if the start month and the end month are the same
endDate.Day < startDate.Day// AND the end day is less than the start day
|| endDate.Month < startDate.Month)// OR if the end month is less than the start month
{
years--;
}
return years;
}
var totalYears =
(DateTime.Today - new DateTime(2007, 03, 11)).TotalDays
/ 365.2425;
Wikipedia / Leap_year의 평균 일수 .
분수 연도를 처리하는 방법은 명확하지 않지만 아마도 다음과 같습니다.
DateTime now = DateTime.Now;
DateTime origin = new DateTime(2007, 11, 3);
int calendar_years = now.Year - origin.Year;
int whole_years = calendar_years - ((now.AddYears(-calendar_years) >= origin)? 0: 1);
int another_method = calendar_years - ((now.Month - origin.Month) * 32 >= origin.Day - now.Day)? 0: 1);
두 날짜 사이의 연수를 전체 월로 반올림하여 가져 오는 확장 방법을 구현했습니다.
/// <summary>
/// Gets the total number of years between two dates, rounded to whole months.
/// Examples:
/// 2011-12-14, 2012-12-15 returns 1.
/// 2011-12-14, 2012-12-14 returns 1.
/// 2011-12-14, 2012-12-13 returns 0,9167.
/// </summary>
/// <param name="start">
/// Stardate of time period
/// </param>
/// <param name="end">
/// Enddate of time period
/// </param>
/// <returns>
/// Total Years between the two days
/// </returns>
public static double DifferenceTotalYears(this DateTime start, DateTime end)
{
// Get difference in total months.
int months = ((end.Year - start.Year) * 12) + (end.Month - start.Month);
// substract 1 month if end month is not completed
if (end.Day < start.Day)
{
months--;
}
double totalyears = months / 12d;
return totalyears;
}
다음은 시스템이 윤년을 자동으로 처리 할 수있는 깔끔한 트릭입니다. 모든 날짜 조합에 대한 정확한 답을 제공합니다.
DateTime dt1 = new DateTime(1987, 9, 23, 13, 12, 12, 0);
DateTime dt2 = new DateTime(2007, 6, 15, 16, 25, 46, 0);
DateTime tmp = dt1;
int years = -1;
while (tmp < dt2)
{
years++;
tmp = tmp.AddYears(1);
}
Console.WriteLine("{0}", years);
누군가의 나이를 얻으려면 이걸보세요
int Age = new DateTime((DateTime.Now - BirthDateTime).Ticks).Year;
public string GetAgeText(DateTime birthDate)
{
const double ApproxDaysPerMonth = 30.4375;
const double ApproxDaysPerYear = 365.25;
int iDays = (DateTime.Now - birthDate).Days;
int iYear = (int)(iDays / ApproxDaysPerYear);
iDays -= (int)(iYear * ApproxDaysPerYear);
int iMonths = (int)(iDays / ApproxDaysPerMonth);
iDays -= (int)(iMonths * ApproxDaysPerMonth);
return string.Format("{0} år, {1} måneder, {2} dage", iYear, iMonths, iDays);
}
TimeSpan에서 몇 년, 몇 달, 며칠 동안 이것을 발견했습니다 .
DateTime target_dob = THE_DOB;
DateTime true_age = DateTime.MinValue + ((TimeSpan)(DateTime.Now - target_dob )); // Minimum value as 1/1/1
int yr = true_age.Year - 1;
달과 년을 다루려면 매달 몇 일이 있고 어떤 년이 윤년인지 아는 것이 필요합니다.
Calendar는 두 시점의 차이를 직접 계산하는 방법을 제공하지 않지만 다음과 같은 방법을 가지고 있습니다.
DateTime AddWeeks(DateTime time, int weeks)
DateTime AddMonths(DateTime time, int months)
DateTime AddYears(DateTime time, int years)
DateTime musteriDogum = new DateTime(dogumYil, dogumAy, dogumGun);
int additionalDays = ((DateTime.Now.Year - dogumYil) / 4); //Count of the years with 366 days
int extraDays = additionalDays + ((DateTime.Now.Year % 4 == 0 || musteriDogum.Year % 4 == 0) ? 1 : 0); //We add 1 if this year or year inserted has 366 days
int yearsOld = ((DateTime.Now - musteriDogum).Days - extraDays ) / 365; // Now we extract these extra days from total days and we can divide to 365
완벽하게 작동 :
internal static int GetDifferenceInYears(DateTime startDate)
{
int finalResult = 0;
const int DaysInYear = 365;
DateTime endDate = DateTime.Now;
TimeSpan timeSpan = endDate - startDate;
if (timeSpan.TotalDays > 365)
{
finalResult = (int)Math.Round((timeSpan.TotalDays / DaysInYear), MidpointRounding.ToEven);
}
return finalResult;
}
간단한 솔루션 :
public int getYearDiff(DateTime startDate, DateTime endDate){
int y = Year(endDate) - Year(startDate);
int startMonth = Month(startDate);
int endMonth = Month(endDate);
if (endMonth < startMonth)
return y - 1;
if (endMonth > startMonth)
return y;
return (Day(endDate) < Day(startDate) ? y - 1 : y);
}
이것은 년과 월의 차이를 계산하는 가장 좋은 코드입니다.
DateTime firstDate = DateTime.Parse("1/31/2019");
DateTime secondDate = DateTime.Parse("2/1/2016");
int totalYears = firstDate.Year - secondDate.Year;
int totalMonths = 0;
if (firstDate.Month > secondDate.Month)
totalMonths = firstDate.Month - secondDate.Month;
else if (firstDate.Month < secondDate.Month)
{
totalYears -= 1;
int monthDifference = secondDate.Month - firstDate.Month;
totalMonths = 12 - monthDifference;
}
if ((firstDate.Day - secondDate.Day) == 30)
{
totalMonths += 1;
if (totalMonths % 12 == 0)
{
totalYears += 1;
totalMonths = 0;
}
}
The following is based off Dana's simple code which produces the correct answer in most cases. But it did not take in to account less than a year between dates. So here is the code that I use to produce consistent results:
public static int DateDiffYears(DateTime startDate, DateTime endDate)
{
var yr = endDate.Year - startDate.Year - 1 +
(endDate.Month >= startDate.Month && endDate.Day >= startDate.Day ? 1 : 0);
return yr < 0 ? 0 : yr;
}
Maybe this will be helpful for answering the question: Count of days in given year,
new DateTime(anyDate.Year, 12, 31).DayOfYear //will include leap years too
Regarding DateTime.DayOfYear Property.
I hope the link below helps
MSDN - DateTime.Subtract.Method (DateTime)
There's even examples for C# there. Just simply click the C# language tab.
Good luck
참고URL : https://stackoverflow.com/questions/4127363/date-difference-in-years-using-c-sharp
'Program Tip' 카테고리의 다른 글
Java에서 부울 배열 채우기 (0) | 2020.10.25 |
---|---|
Hudson과 CruiseControl for Java 프로젝트의 차이점은 무엇입니까? (0) | 2020.10.25 |
Eclipse LogCat 뷰어에서 태그 이름을 필터링하는 방법 (0) | 2020.10.25 |
SQL Server에서 VARCHAR 열의 최대 길이 검색 (0) | 2020.10.25 |
'ProviderPackage'패키지가 올바르게로드되지 않았습니다. (0) | 2020.10.25 |