1

I have a ridiculous string provided by data that isn't adjustable and I need to convert it to a timestamp in a consistent manner.

5162016

sometimes 2 digit month, sometimes leading zeros sometimes not.

I tried using DateTime

$time = \DateTime::createFromFormat("njY", "5162016");
$timestamp = $time->getTimestamp();

I tried both njY and mdY but both return a timestamp that converts to 05/01/0020

Any ideas would be appreciated.

2
  • Looked at php.net/strtotime? Commented Apr 10, 2016 at 12:44
  • 1
    Perhaps you could check the string length. But it would be impossible to differentiate 1122016 between 12 January and 2 November unless the day portion consistently has a leading zero. Commented Apr 10, 2016 at 12:48

1 Answer 1

1

Normalize your data, so that the month will be always with a leading zero.

$normalizedDate = str_pad("5162016", 8, 0, STR_PAD_LEFT);
$time = \DateTime::createFromFormat("mdY", $normalizedDate);
$timestamp = $time->getTimestamp();

This only works if the Day of the month is always a 2 digits with leading zeros.

Sign up to request clarification or add additional context in comments.

3 Comments

Isn't clear if there is a leading zero for the day portion. Unless there is, this cannot be used reliably.
So, both months and days can or cannot have leading zero? one time just month, another just day, some time both? then there's no way to distinguish them
Perhaps a combination? Remove the last 4 since that's the only reliable section. Then count the remaining characters. 2 and 4 should be reliable knowing we have either both 2 digit or both 1 digit. 3 on the other hand ... I would think perhaps if the first digit is not 0 or 1, then we have a single digit month, and can pad that with 0. Otherwise we have a 2 digit month and the day is the single. Is something like this possible?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.