Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the last 2 digits a number

Tags:

php

How can I get the last 2 digits of:

<departureDate>200912</departureDate>

to my object:

$year = $flightDates->departureDate->year;
like image 443
UI Developer Avatar asked Sep 28 '12 12:09

UI Developer


People also ask

How do you extract the last two digits of a number?

Last two digits of a number is basically the tens place and units place digit of that number. So given a number say 1439, the last two digits of this number are 3 and 9, which is pretty straight forward.

How do you get the last two digits of a number in typescript?

To get the last 2 digits of a number:Call the slice() method on the string, passing it -2 as a parameter. The slice method will return the last 2 characters in the string. Convert the string back to a number to get the 2 last digits.


2 Answers

// first two
$year = substr($flightDates->departureDate->year, 0, 2);
// last two
$year = substr($flightDates->departureDate->year, -2);

But given the fact that you're parsing a date here it would be smarter to use the date function. p.e. strtotime() and date() or even:

<?php
$someDate ='200912';
$dateObj = DateTime::createFromFormat('dmy', $someDate);
echo $dateObj->format('Y');
// prints "2012" .. (see date formats)
like image 82
Jan. Avatar answered Oct 17 '22 18:10

Jan.


You can just address it as string, the function substr will convert it automatically:

<?php

//$year = '200912';
$year = $flightDates->departureDate->year;

echo substr( $year, -2 );

?>

Take a closer look at substr function. If you want the result to be a strict integer, then just add (int) in front of the return.

But, as Jan. said, you should better work with it as a date:

<?php

//$year = '200912';
$year = $flightDates->departureDate->year;

$date = DateTime::createFromFormat( 'dmy', $year );

echo date( "y", $date->getTimestamp() );

?>
like image 22
Peon Avatar answered Oct 17 '22 16:10

Peon