It is narrated from Sayyiduna Abu Dharr (may Allah be pleased with him), he says: I asked, "O Messenger of Allah! Which mosque was built first?" He (peace and blessings be upon him) said: "Al-Masjid al-Haram." I asked: "Then which was built after that?" He (peace and blessings be upon him) said: "Al-Masjid al-Aqsa." I asked: "What was the time span between the two?" He (peace and blessings be upon him) said: "Forty years." Then he (peace and blessings be upon him) said: "Wherever the time of prayer finds you, perform the prayer there, for that is a mosque."
Hadith Referenceالفتح الربانی / بيان قصص أنبياء الله عليهم السلام / 10347
Hadith Gradingمحدثین:صحیح
Hadith Takhrij«أخرجه البخاري: 3366، 3425، ومسلم: 520 ، (انظر مسند أحمد ترقيم الرسالة: 21390 ترقیم بيت الأفكار الدولية: 21718»
Brief Explanation
Benefits: … It is well-known that Ibrahim (alayhis salam) constructed the Sacred Mosque (Masjid al-Haram) and Sulayman (alayhis salam) constructed the Aqsa Mosque (Masjid al-Aqsa), but there is a gap of more than a thousand years between these two prophets, whereas in this hadith a gap of forty years is mentioned.
Hafiz Ibn Hajar, after presenting various opinions, has answered this objection. We will mention this answer in summary: Neither was Ibrahim (alayhis salam) the first person to construct the Ka‘bah, nor was Sulayman (alayhis salam) the first person to construct Masjid al-Aqsa. We have found a narration according to which Adam (alayhis salam) was the first to construct the Ka‘bah, then his progeny spread throughout the earth, and it is possible that someone constructed Bayt al-Maqdis (Jerusalem) at that time. Some are of the opinion that perhaps before Dawud (alayhis salam), a friend of Allah (wali) constructed Masjid al-Aqsa, and then Dawud (alayhis salam) and Sulayman (alayhis salam) expanded it. Others hold the view that Adam (alayhis salam), or the angels, or Sam bin Nuh, or Ya‘qub (alayhis salam) laid the foundation of Masjid al-Aqsa, and Sulayman (alayhis salam) completed it. According to the narration of Ibn Hisham, Adam (alayhis salam) laid the foundation of both mosques, then during the flood of Nuh (alayhis salam), the House of Allah (Bayt Allah) was raised, and Ibrahim (alayhis salam) reconstructed it. (Fath al-Bari: 6/408, 409)
The summary of this discussion is that before Ibrahim (alayhis salam) and Sulayman (alayhis salam), the Sacred Mosque and Masjid al-Aqsa were constructed, but for various reasons their traces became weak, then these two prophets reconstructed them, and thus these mosques became attributed to them.