कई साल पहले, मेरी वेबसाइट पर एक आयु कैलक्यूलेटर gimmick प्रदान करने के लिए, मैंने उम्र की गणना करने के लिए एक फ़ंक्शन लिखा था अंश। यह उस फ़ंक्शन का त्वरित पोर्ट है C# ( से PHP संस्करण )। मुझे डर है कि मैं सी # संस्करण का परीक्षण करने में सक्षम नहीं हूं, लेकिन आशा है कि आप सभी का आनंद लेंगे!
(माना जाता है कि यह स्टैक ओवरफ़्लो पर उपयोगकर्ता प्रोफाइल दिखाने के प्रयोजनों के लिए थोड़ा सा गड़बड़ है, लेकिन शायद पाठकों को इसके लिए कुछ उपयोग मिलेगा। :-))
double AgeDiff(DateTime date1, DateTime date2) {
double years = date2.Year - date1.Year;
/*
* If date2 and date1 + round(date2 - date1) are on different sides
* of 29 February, then our partial year is considered to have 366
* days total, otherwise it's 365. Note that 59 is the day number
* of 29 Feb.
*/
double fraction = 365
+ (DateTime.IsLeapYear(date2.Year) && date2.DayOfYear >= 59
&& (date1.DayOfYear < 59 || date1.DayOfYear > date2.DayOfYear)
? 1 : 0);
/*
* The only really nontrivial case is if date1 is in a leap year,
* and date2 is not. So let's handle the others first.
*/
if (DateTime.IsLeapYear(date2.Year) == DateTime.IsLeapYear(date1.Year))
return years + (date2.DayOfYear - date1.DayOfYear) / fraction;
/*
* If date2 is in a leap year, but date1 is not and is March or
* beyond, shift up by a day.
*/
if (DateTime.IsLeapYear(date2.Year)) {
return years + (date2.DayOfYear - date1.DayOfYear
- (date1.DayOfYear >= 59 ? 1 : 0)) / fraction;
}
/*
* If date1 is not on 29 February, shift down date1 by a day if
* March or later. Proceed normally.
*/
if (date1.DayOfYear != 59) {
return years + (date2.DayOfYear - date1.DayOfYear
+ (date1.DayOfYear > 59 ? 1 : 0)) / fraction;
}
/*
* Okay, here date1 is on 29 February, and date2 is not on a leap
* year. What to do now? On 28 Feb in date2's year, the ``age''
* should be just shy of a whole number, and on 1 Mar should be
* just over. Perhaps the easiest way is to a point halfway
* between those two: 58.5.
*/
return years + (date2.DayOfYear - 58.5) / fraction;
}