The answer will potentially depend on a number of factors, including the country and the size of the airport.
From personal experience in the US, I would not expect you to have any issues entering several hours after the flight was scheduled to depart - presuming it was still on the same calendar day, and presuming there were still flights due to depart from the airport that night. I've passed through security in multiple countries (including the US, Japan and the UAE) on multiple occasions with a boarding pass for a flight that was scheduled to depart several hours before I was entering - always without issue.
However it's certainly possible that the security staff will look at the time on the ticket and ask about it. In this case you would have the option of claiming you missed the flight and are going to the customer service desk to get re-routed (but expect to be sent back to the check-in desk instead), or claim that your flight is delayed - odds are the security staff will not bother to confirm this.
If you try and enter after midnight then it will be a different story. I recently entered an airport at around 6am using a boarding pass for a delayed flight from the previous day. The security staff had a (small) list of flights that has been delayed overnight, and confirmed that my flight was on that list before they let me proceed.
Whether what you are suggesting is legal is a different issue altogether, and again will depend on the specific airport. If this was in the US you would be fraudulently accessing the airside area of a federally controlled facility, which is almost certainly illegal in some way or other. Your odds of actually getting caught will, again, depend on the specific location.