I am posting this optimistically after searching for an answer here on SO, and even when SO tells me my question might be closed, as I think in this case it's a valid question.
Consider a CSV file with a column containing string representing either dates, or times, or both. I want to find out after reviewing the column, just that - exactly what type of column is it, not just that it's a valid "date"?
PHP function strtotime does an amazing job of returning a unix timestamp for pretty much any date-time-ish string. But (today when I'm posting this on 10/8/2018), 3:45PM
and 15:45:00
and 10/8/2018 3:45PM
would all return the same unix time, though obviously the first two are times.
What is a method to determine if a string is strictly a date component, a time component, or both?
P.S. If I have to write a function myself, so far the best lead would be to look for a :
in the string, which would mean there's a time component (meaning either time, or datetime). If it parses as a datetime, but with no :
present, then we could assume it's a date only. But again, I am wondering if PHP has a more elegant way. Here is a "pretty good" solution:
P.P.S this function is actually a "very good" solution now thanks to @KarstenKoop's clever suggestion in comments about the 2nd parameter for strtotime
:
function date_time_component($date){
if(strtotime($date) === false) return false;
if(strtotime($date, 86400) !== strtotime($date, 86400 * 2)) return 'time';
if(strstr($date, ':')) return 'datetime';
return 'date';
}