I asked the Messenger of Allah ﷺ, "Which mosque was built first?"He replied, "The Sacred Mosque."I asked, "Then which?"He said, "The Aqsa Mosque."I asked, "How long was there between them?"He answered, "Forty years. And the earth is a mosque for you, so wherever the time of prayer overtakes you, pray."
أخبرنا علي بن حجر قال حدثنا علي بن مسهر عن الأعمش عن إبراهيم قال كنت أقرأ على أبي القرآن في السكة فإذا قرأت السجدة سجد فقلت يا أبت أتسجد في الطريق فقال إني سمعت
سألت رسول الله ﷺ أي مسجد وضع أولا قال المسجد الحرام قلت ثم أي قال المسجد الأقصى قلت وكم بينهما قال أربعون عاما والأرض لك مسجد فحيثما أدركت الصلاة فصل
Muslim narrated it in Sahih Muslim, Masjids, chapter on masjids and places of prayer, hadith 2/520, from Ali bin Hajar, and Bukhari narrated it, Stories of the Prophets, chapter (10), hadith 3366, from the hadith of Amash with the same wording, and it is also in Kubra, hadith 769.