The simple answer is that a chapter 7 bankruptcy filing stays on your credit report for 10 years and a chapter 13 for 7 years. However, the negative effect on your credit score will likely be much shorter.
Most people do not have high credit scores when they file bankruptcy. They have usually fallen behind on payments to creditors. When you fall behind, each month every creditor that is behind hits your credit report with negative feedback, which could be several hits per month. A bankruptcy filing dings your credit report negatively one time, but it stops all those repeated negative hits. Once you file bankruptcy, creditors cannot report negatively on your credit report. Thus, while bankruptcy will likely cause your credit score to decrease upon filing, every month thereafter when you are no longer getting repeated negative hits, you will be building your score back up. It is not unusual for someone to have a higher credit score a year after filing bankruptcy than they had on the day they filed.
Also, the lower your credit score is, the less it can fall when you file bankruptcy. Once bills start getting behind, your credit score is going to tank anyway. Filing bankruptcy can stop the fall.
In reality, in many cases, filing bankruptcy results in an improved credit score.