When and how was the length of a Mars year determined? I guess it is known for a long time that Mars has an orbital period of around 687 days.

But when and how was this determined?
There are two answers to this, because the period "687" was known long before it was recognised as an "orbital period".

The Babylonians knew by 600 BCE that Mars took 79 years to go through all 12 constellations 42 times, giving a period of 79/42 × 365.25 = 687 days.  But they wouldn't have thought of this as an "orbit" (in the modern sense) since they would not have thought of Mars as being a physical object. Similar knowledge was known in India and China.  It is relatively easy to determine, and just requires the intent to measure and the ability to make careful records.  This value was known wherever people had writing, an interest in the stars, and a stable enough society.

The understanding of the value as being "the time for Mars to orbit the sun once" depends on having a heliocentric, so is due to Aristarchus, Copernicus, Kepler, or Newton (depending on what you mean by "know that Mars orbits the sun")