Computer

Convert TimeSpan to year, month, date (Age Calculation) in .NET

창천(蒼天) 2014. 8. 22. 11:19

출처 : http://techbrij.com/convert-timespan-to-year-month-date-age-calculation-in-net




private string 년월일구하기(DateTime t1,DateTime t2)
{
    int 일 =t2.Day - t1.Day;
    int 월 =t2.Month-t1.Month;
    int 년 =t2.Year-t1.Year;
    if (일<0)
    {
        일+=DateTime.DaysInMonth(t2.Year,t2.Month-1);
        월--;
    }
    if(월<0)
    {
        월+=12;년--;
    }
    return 년.ToString()+"-"+월.ToString()+"-"+일.ToString() ;
}



public void TimeSpanToDate(DateTime d1, DateTime d2,out int years, out int months, out int days)
{
    // compute & return the difference of two dates,
    // returning years, months & days
    // d1 should be the larger (newest) of the two dates
    // we want d1 to be the larger (newest) date
    // flip if we need to
    if (d1 < d2)
    {
        DateTime d3= d2;
        d2= d1;
        d1= d3;
    }
 
    // compute difference in total months
    months= 12 * (d1.Year - d2.Year) + (d1.Month - d2.Month);
 
    // based upon the 'days',
    // adjust months & compute actual days difference
    if (d1.Day < d2.Day)
    {
        months--;
        days = DateTime.DaysInMonth(d2.Year, d2.Month) - d2.Day + d1.Day;
    }
    else
    {
        days= d1.Day - d2.Day;
    }
    // compute years & actual months
    years= months / 12;
    months-= years * 12;
}