Reputation: 75
We are designing a new sensor that sends some data to a webapplication. We use similar sensors, but they use data channels to divide the value send to the application into different data types.
However, this new sensor will send either data or a 32 bit time, with miliseconds. It doesn't send a identifier bit to see whether the value is data or a timestamp.
Because both the data and timestamp are integer value's, How can i check which one it is?
The timestamp will be
YYYY/MM/DD HH:MI:SS:vv
I already found preg_match, like this:
if (preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}/', $value))
But how do i include the miliseconds? Or is there a better way than a simple if else?
Update
I expect that the date recieved by the application will be in int16. So it might be easier to count the values recieved and handle value 9 and 10 like datetimes..
Upvotes: 2
Views: 1707
Reputation: 75
I fixed it in a different way:
we determined that the first 2 16bit values in a message are always the timestamps, so i just made a valuecounter and used a if $value is 1 or 2 then do this, else do that. This was a lot easier for me then to check each value.
Upvotes: 0
Reputation: 4579
You could use the createFromFormat()
method from the PHP DateTime object.
You would create a function that checks the method errors :
function is_valid_date($date, $format = 'Y/m/d H:i:s.u')
{
$d = DateTime::createFromFormat($format, $date);
$errors = DateTime::getLastErrors();
return (
$errors['warning_count'] == 0 &&
$errors['error_count'] == 0 &&
$d !== false
);
}
Hope it helps.
EDIT :
Added the u
(for microseconds) on the default format.
Upvotes: 5
Reputation: 955
You could use this regular expression:
With preg_match_all
:
preg_match_all("/(\d{4})\/(\d{2})\/(\d{2})\s(\d{2})\:(\d{2})\:(\d{2})\:(\d{2})/", $input_lines, $output_array);
With preg_match
:
preg_match("/(\d{4})\/(\d{2})\/(\d{2})\s(\d{2})\:(\d{2})\:(\d{2})\:(\d{2})/", $input_line, $output_array);
Beware, it only checks for the numbers, the backslashes and the ':' character. It doesn't check if the given numbers are valid.
Once you've run the regular expression, you can then check the output array and see if it's empty or not (if it isn't empty it matched the format)
The regular expression matches this range:
0000/00/00 00:00:00:00
9999/99/99 99:99:99:99
Upvotes: 1