user12311699
user12311699

Reputation: 59

Get date from a string

I have a string like this G5510ZCU1AQG2.

the QG last letters represent a date formatted like this 2017-07.

the letter q represent the year . and g the month.

you keep count the letters to get the number.

I want to get the date from these letters .

I tried to make switch statement but its not helpful and there is a lot of code to write.

is there simpler way to get the date as 2017-07 from this string G5510ZCU1AQG2?

I'm sorry i'm still learning and i can't think of something useful

Upvotes: 0

Views: 59

Answers (1)

Pavel Lint
Pavel Lint

Reputation: 3527

Here's how you can do that:

$str = "G5510ZCU1AQG2";

$year_letter = substr($str, -3, 1);
$month_letter = substr($str, -2, 1);

$year = 2000 + (ord($year_letter) - ord('A') + 1);
$month = ord($month_letter) - ord('A') + 1;

$date = sprintf("%02d-%d", $month, $year);

Explanation

  • First we dig out the letters for year and month using substr. Passing -3 and 1 means "get me 1 letter which is located 3 away from the end".
  • Then we get the ASCII code of the letter with ord(). Comparing it to the ASCII code of the first letter A gives us the number of the letter in the alphabet (+1 because it starts with 1, not with 0)
  • Now that we know the values, we can get the date as $month . "-" . $year. However, this would give us 7-2017 and we want a leading zero. That's what the sprintf function is used for: "%02d-%d means "print a 2-digit number with a leading zero, then a minus sign, then a digit.
  • Output of this code: "07-2017"

Cheers.

Upvotes: 1

Related Questions