The baby's gonads turn into testes for boys or ovaries for girls at about 8-9 weeks. The gender is already determined but this is when the different developments start.
Every sperm has either an x or a y chromosome and the moment it combines with the egg, that determines the gender of the baby. It's just not outwardly obvious until around 18 weeks or so. A lot of people find out at 20.
Gender is determined right when the egg is fertilized. Just can't see it on u/s.
Already determined by the sperm
It's detectable by ultrasound usually between 18-22 weeks