Sayyiduna Abdullah bin Mas'ud, may Allah be pleased with him, says: The Messenger of Allah, peace and blessings be upon him, told us—and he was very truthful: "Your creation is gathered in your mother's womb for forty days, then it becomes a clot of blood, then for such a period it becomes a morsel of flesh, then an angel comes and writes down whether he is fortunate or unfortunate and whether he is male or female."
Related hadith on this topic