According to HowStuffWorks, the time required for a caterpillar to pupate (change into an adult butterfly or moth) averages about two weeks. However, the exact time that the caterpillar stays in the cocoon varies by species.
After spending most of its life eating, a caterpillar finds a safe spot to pupate and forms a protective shell, called a chrysalis, around its body. Moth caterpillars may spin a silk cocoon to protect the chrysalis until the moth is ready to emerge. The cocoon starts out soft, but gradually hardens to offer better protection. Certain species spend the winter in their cocoon, transforming over several months, but most accomplish their metamorphosis in a few weeks.