"When your days are fulfilled, etc." (2 Samuel 7:12). Rabbi Shmuel bar Nachman said: [The Holy One, blessed be He, said to him: David,] full days of days I am counting for you; I am not counting [for you] deficient days. "And the days that David reigned over Israel were forty years" (1 Kings 2:11), and it is written, "In Hebron he reigned over Judah seven years and six months, and in Jerusalem he reigned thirty-three years" (2 Samuel 5:5). These extra ones (here) [that are here], what are they? Rabbi Yitzchak bar Ketzarta in the name of Rabbi Yonah: They were deficient, but the Scriptures show honor to Jerusalem and count them as full ones. Rabbi Yudan said: The larger reckoning swallows up the smaller reckoning. Since it is written, "For six months Yoav remained there, etc." (1 Kings 11:16), those six months did not enter into the count. Rabbi Yudan said: All those six months that David was fleeing from before Avshalom his son did not enter into his count for him, but through a goat he was atoned for like a commoner.
How the Sages Counted David's Forty Years of Reign
Midrash Shmuel 26:5
כי ימלאו ימיך וגו' (שמואל ב' ז' י"ב), אמר רבי שמואל בר נחמן [אמר לו הקדוש ברוך הוא דוד] ימים של ימים אני מונה לך, איני מונה [לך ימים] חסירים, והימים אשר מלך דוד על ישראל ארבעים שנה (מלכים א' ב' י"א), וכתיב בחברון מלך על יהודה שבע שנים וששה חדשים ובירושלים מלך שלשים ושלש שנה (שמואל ב' ה' ה'), אילין יתירייא (והכא) [דהכא] מה אינון, רבי יצחק בר קצרתה בשם ר' יונה חסירין היו אלא שהכתובין חולקין כבוד לירושלם ומונין אותן שלימים, אמר רבי יודן חשבון מרובה בולע לחשבון מועט לפי שכתוב כי ששת חדשים ישב שם יואב וגו' (מלכים א' י"א ט"ז), אותן ששה חדשים לא עלו מן המנין, אמר רבי יודן כל אותן ששה חדשים שהיה דוד בורח מפני אבשלום בנו לא עלו לו מן המנין, אלא בשעירה נתכפר לו כהדיוט.