-1

Any ideas how I can make a simple IF-statement that sort 31-10-2017 or 12-01-2016 from 1511431687?

I am converting from a set date, to use unix timestamp, and need a solution to sort out what is what. I want to display the date in human readable format (days/ month/year).

So I have a $data that is inside a loop. It pulls the date from a flat file. The old stuff has just saved the date as a date. For instance 31-10-2017 (exactly like that).

Now I use unix timestamp. For instance 1511431687.

I see people have used a simple IF-statement, but I can not use it as both are 10 units long. Else that would have worked well.

$data = // either a timestamp, or a date in this format: 31-10-2017

if (strlen($data) === 10) // it's a timestamp   
$data =  date("d-m-Y H:i:s", $data);
Eddie
  • 26,593
  • 6
  • 36
  • 58
Preben
  • 1,277
  • 2
  • 11
  • 20
  • 1
    `if (strpos($data, '-') === false) // it's a timestamp` (assumes positive timestamps); adjust if you might have timestamps before the 1970 timestamp base date – Mark Baker Dec 07 '17 at 13:26
  • So you're looking for a regex for date? Or timestamp? Timestamp is shorter, `\d{10}`. – pavel Dec 07 '17 at 13:27
  • @RolandStarke: OP wrote _both are 10 units long_, so both are the same length. At least in this case. – pavel Dec 07 '17 at 13:29
  • @MarkBaker https://meta.stackexchange.com/questions/230676/hey-you-yeah-you-post-your-answers-as-answers-not-comments/296481#296481 You are not seeking clarification, you are providing a solution. Please post in the correct location. – mickmackusa Dec 07 '17 at 13:50
  • Possible duplicate of [$var is valid unix timestamp](https://stackoverflow.com/questions/4123541/var-is-valid-unix-timestamp) – mickmackusa Dec 07 '17 at 14:09

2 Answers2

3

Maybe naive, but a solution might be to check if $data has a numeric value.

if (is_numeric($data)) { // it's a timestamp   
    $data =  date("d-m-Y H:i:s", (int) $data);
}
l-x
  • 1,521
  • 9
  • 17
0

You have several options:

Depending on how many different formats you expect, I'd try in this logical order:

  • if ctype_digit, check if value is in expected range
    • if outside expected range, try dividing by 1000 (timestamps in milliseconds)
  • otherwise, try matching with a regex in whatever formats you expect
    • confirm with checkdate that the values are sensible
  • finally convert to DateTime object as standardised internal representation
deceze
  • 510,633
  • 85
  • 743
  • 889