You will be detained only for as long as you continue to meet the criteria for detention (see above).
Detention under s2 will last for a maximum of 28 days. This period cannot be extended but if you are assessed as remaining unwell at the end of it, you can be assessed for detention under s3 instead.
Detention under s3 lasts initially for a period of up to 6 months. It can then be renewed for a further 6 months and, after that, for periods of 12 months at a time. Detention can only be renewed if you are assessed as continuing to meet the criteria for detention.
Detention under s37 follows the same pattern as s3.