This set of examples was inspired by a novice colleague wrote the code shown in example 1. The code was intended to convert a string representation of a Posix timestamp into a DateTime object, but does it very inefficiently. It converts the timestamp to a formatted date string, then to a timestamp integer, and finally to a DateTime object, with the call to the DateTime constructor converting the integer into a string prefixed with "@".
Examples 2 and 3 show the conversion can be done in fewer steps.
Because the original code wrapped these conversions in a test for is_string($startTime)
test, example 4 demonstrates what would happen if the string doesn't contain what was expected. For example, a human-readable date format. Exceptions are thrown.
Example 5 shows how the code could deal with the Posix vs. human-readable timestamps by attempting to use the first format, then falling back to use the other. I'm still unsure whether it's proper to just drop the first exception if the first attempt fails. Instead, should it be thrown if the second attempt fails?
Example 6 resolves the multiple exception question by attempting to use a single DateTime constructor call to handle multiple formats of the timestamp input. It handles the possibility of the input being a Posix timestamp, either as a string or an integer, by checking it with is_numeric()
and prefixing an "@" if needed. Either way, the input is converted to a string, to be safe.