You can't; just use the good common sense that people have been using since they were invented, nose, look, taste. Expiry dates are generally only guides anyway.
If a raw food you have bought is close to expiry date, cook it, that will give it a few more days as long as it is kept in the fridge.
Remember, it isn't a good idea to scrape mould off food and eat the remainder, the 'roots' tend to be hardly visible and stretch a long way into the food.
The fats and sugars in cakes and pastries help preserve the food stuff, the legend being, hot x buns never go off? In rich, fruit cakes, the high fruit, sugar and alcohol content helps them last a long time: the bit of wedding cake saved for the first anniversary. It is still best to keep sweet cakes and pastries in close fitting, better still, airtight containers.
Finally, always protect all food stuffs from the attention of flies.