I found the answer on Quora because I didn’t know the answer to this.
To determine the expiry date of food, a microbial test is conducted over a given time frame.
For example, to measure the expiry date of a cake, a company would send out the cake samples to a lab and initial level of microbial activity will be measured and it will be repeated over several days. Generally, individual companies have their own threshold level of microbial activity, so the expiry date is that date after manufacturing when the microbial activity reaches that threshold level
Comments