-1

I was testing some strings (countries) with the

strtotime()

function and foud out that :

  • 'Poland' does returns a timestamp, but 'Soland' or anything else like this does not.
  • 'GB' does too.

Going farther, 'a string' is also returning something, juste like some simple Letters like 'G' or 'P'.

Those strings are not listed in the datetime relative formats doc.

I might be dumb but I didn't find anything on those special cases, what is actually going on ?

And second less important question : how to actually check if a string is a valid date format excluding those "special" strings, knowing I don't know the format in advance ?

Thomas
  • 108
  • 8
  • 3
    While there's probably some specific reason one can dig into, `strtotime` isn't the tool to validate date strings in the first place, as it accepts "next year" and "+1 month" and such very officially… – deceze Sep 24 '21 at 13:01
  • 1
    https://stackoverflow.com/questions/10119671/how-algorithm-of-strtotimephp-date-function-works Links to some more technical aspects of the function – aynber Sep 24 '21 at 13:03
  • 1
    _"And how to actually check if a string is a valid date format excluding those "special" strings ?"_ - can we please do a bit of basic research, before we ask? "php check date is valid" typed into Google, leads you to https://stackoverflow.com/questions/19271381/correctly-determine-if-date-string-is-a-valid-date-in-that-format/19271434 in no time ... – CBroe Sep 24 '21 at 13:19
  • *And how to actually check if a string is a valid date format*, have an array of valid accepted formats, use key for format and value for regex match, loop over them, on first matched, use the format to pass into DateTime::createFromFormat with the value, then validate min-max or from, to etc – Lawrence Cherone Sep 24 '21 at 13:23
  • I don't know the format i'll get thats why strtotime was usefull. My question was more on why this is happening. But that's ok I'll dig myself into the source code to find out, and make my own date checking. Thanks. – Thomas Sep 24 '21 at 13:43
  • Not knowing the format of some input date is a recipe for disaster. Is 1/2/3 January 2nd 2003, or February 1st, or nonsense? – deceze Sep 24 '21 at 13:57

1 Answers1

2

DateTime accepts the same arguments as strtotime. The argument 'GB' used for DateTime shows that 'GB' is recognized as the time zone.

var_dump(new DateTime('GB'));
/*
object(DateTime)#3 (3) {
  ["date"]=>
  string(26) "2021-09-24 16:54:37.568996"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(2) "GB"
}
*/

Like 'Poland', 'GB' is also represented in the list of Others time zones. 'Soland' not. DateTime then provides the current time ('Now') for a correctly recognized time zone.

jspit
  • 7,276
  • 1
  • 9
  • 17