How do they know how long you live with cancer?

Individualize. It depends on the type of cancer and whether or not it had spread (staging). It also depends on your current health status/age/ability to handle treatment...
Depends. Some cancers, e.g., small cell cancer of the lung can kill in months from the time of initial detection, other cancers are slow growing and a person may for years or even decades. Successful treatment can obviously cure some cancers and prolong life in others.