[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString datediff2(SqlDateTime Date1, SqlDateTime Date2, string StringFormat=" {0} yıl, {1} ay, {2} gün")
{
// date1 is small one-- date2 is biggest one
int years = 0;
int months = 0;
int days = 0;
string buff = string.Empty;
DateTime currentDate = Date1.Value;
DateTime datetarget = Date2.Value;
DateTime tmpMyDOB = new DateTime(datetarget.Year, datetarget.Month, 1);
DateTime tmpFutureDate = new DateTime(currentDate.Year, currentDate.Month, 1);
while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)
{
months++;
if (months > 12)
{
years++;
months = months - 12;
}
}
if (currentDate.Day >= datetarget.Day)
{
days = days + currentDate.Day - datetarget.Day;
}
else
{
months--;
if (months < 0)
{
years--;
months = months + 12;
}
days +=
DateTime.DaysInMonth(
currentDate.AddMonths(-1).Year, currentDate.AddMonths(-1).Month
) + currentDate.Day - datetarget.Day;
}
//add an extra day if the dob is a leap day
if (DateTime.IsLeapYear(datetarget.Year) && datetarget.Month == 2 && datetarget.Day == 29)
{
//but only if the future date is less than 1st March
if (currentDate >= new DateTime(currentDate.Year, 3, 1))
days++;
}
buff = string.Format(StringFormat, years, months, days);
buff = buff.Replace(", 0 gün", string.Empty);
buff = buff.Replace(", 0 ay", string.Empty);
buff = buff.Replace(" 0 yıl, ", string.Empty);
return new SqlString(buff);
}
Hiç yorum yok:
Yorum Gönder