-1

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).

Zorono
  • 75
  • 2
  • 12

1 Answers1

0

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

Felippe Duarte
  • 14,901
  • 2
  • 25
  • 29
  • i used DateTime Object just to see whether it works or not (the regex script) – Zorono Jul 10 '18 at 19:01
  • You can't compare an object with string. It will always return false. If you format like the code I wrote here, you will get the output as ISO8601, the format you want. There is no need to validate with a regex. – Felippe Duarte Jul 10 '18 at 19:02
  • so what is the solution ? for some reasons i have to validate the timestamp argument before executing next actions... – Zorono Jul 10 '18 at 19:25
  • What are you trying to do? If you need to generate a ISO8601 date, use the function format. If you need to validate a IS8601 regex, use my regex. If you need to validate a different value, show which value you need to validate, so we can help you. – Felippe Duarte Jul 10 '18 at 19:27
  • it returns `bool(false)` for `2018-07-10T21:32:39.1531251159800+02:00`(Invalid Result) – Zorono Jul 10 '18 at 19:33
  • Updated, take a look. – Felippe Duarte Jul 10 '18 at 19:38