我怎样才能得到最后2位数字:
<departureDate>200912</departureDate>
Run Code Online (Sandbox Code Playgroud)
对我的对象:
$year = $flightDates->departureDate->year;
Run Code Online (Sandbox Code Playgroud)
Jan*_*an. 22
// first two
$year = substr($flightDates->departureDate->year, 0, 2);
// last two
$year = substr($flightDates->departureDate->year, -2);
Run Code Online (Sandbox Code Playgroud)
但鉴于您在这里解析日期这一事实,使用日期函数会更聪明.pe strtotime()和date()甚至:
<?php
$someDate ='200912';
$dateObj = DateTime::createFromFormat('dmy', $someDate);
echo $dateObj->format('Y');
// prints "2012" .. (see date formats)
Run Code Online (Sandbox Code Playgroud)
你可以substr将它作为字符串来解决,函数会自动转换它:
<?php
//$year = '200912';
$year = $flightDates->departureDate->year;
echo substr( $year, -2 );
?>
Run Code Online (Sandbox Code Playgroud)
仔细看看substr函数.如果您希望结果是严格整数,那么只需(int)在返回前添加.
但是,正如Jan.所说,你应该更好地将它作为一个日期:
<?php
//$year = '200912';
$year = $flightDates->departureDate->year;
$date = DateTime::createFromFormat( 'dmy', $year );
echo date( "y", $date->getTimestamp() );
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34694 次 |
| 最近记录: |