so i'm Trying to check whether an variable is with the following format YYYY-MM-DDTHH:MM:SS.MSSZ
(ISO8601 timestamp) using preg_match.
What i have tried:
$timezone = new DateTime("now", new DateTimeZone(date_default_timezone_get()));
var_dump(boolval(preg_match("/^[0-9]{4,4}-[0-9]{2,2}-[0-9]{2,2}T[0-9]{2,2}:[0-9]{2,2}:[0-9]{2,2}(Z)|(\+[0-9]{2,2}:[0-9]{2,2})$/", date("Y-m-d\TH:i:s." .round(microtime(True) * 1000). "\\" . $timezone->format('P')))));
but the var_dump always result in invalid results... For example when i use an timestamp with invalid ISO8601 format
Expected result: bool(false)
and Output: bool(true)
so it result in bool(true)
at most of cases...(it doesn't matter if it's invalid or valid).
DateTime is a object. If you do a var_dump($timezone)
you will see that.
With that information, you can format as you want, like this:
$timezone = new DateTime("now", new DateTimeZone(date_default_timezone_get()));
var_dump($timezone->format(DateTime::ISO8601));
Output
string(24) "2018-07-10T12:00:53-0700"
Now, the regex you are using, isn't the same of you input value.
$timezone = new DateTime("now", new DateTimeZone(date_default_timezone_get()));
$timezone = date("Y-m-d\TH:i:s." .round(microtime(True) * 1000). "\\" . $timezone->format('P'));
echo $timezone; //Will Print 2018-07-10T12:04:34.1531249474906-07:00
var_dump(boolval(preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]+[\-\+][0-9]{2}:[0-9]{2}/", $timezone)));
Now it is true.
Read more here: http://php.net/manual/en/class.datetime.php