问题
I am just trying to extract the date's year
, month
and day
separately so that I can use it as per my wish.
I stored the current date in $today
and used substr()
to extract the strings from it. But I am getting some strange behaviour from what I am doing.
My current code:
$today = date("Y/m/d");
$_year = substr($today, 0,4);
$_month = substr($today, 5,7);
$_day = substr($today, 8, 10);
echo $_year . " " . $_month;
The $_year
works correctly as expected but the problem arises from $_month
, no matter what position I start my substr()
the month and day gets paired up with each other.
Can anyone help me solve this issue? It's driving me crazy.
回答1:
You should have a look at substr
reference: http://php.net/manual/it/function.substr.php
That function accepts 3 parameters: $length
is the length of the string you want to cut starting from $start
string substr ( string $string , int $start [, int $length ] )
In your case, this will work properly:
$today = date("Y/m/d");
$_year = substr($today, 0,4);
$_month = substr($today, 5,2);
$_day = substr($today, 8, 2);
echo $_year." ".$_month;
回答2:
This should work for you:
Just explode() your date by a slash and then use a list() to assign the variables.
list($year, $month, $day) = explode("/", $today);
回答3:
Just use:
echo date("Y m");
If you want to have every part of the date in an individual variable, I highly encourage you to use the DateTime class:
$dt = new DateTime();
$year = $dt->format('Y');
$month = $dt->format('m');
$day = $dt->format('d');
echo $dt->format('Y m');
回答4:
$today = date("Y/m/d");
$_year = substr($today, 0,4);
$_month = substr($today, 5,7);
$_day = substr($today, 8, 10);
echo $_year." ".$_month;
should be
$today = date("Y/m/d");
$_year = substr($today, 0,4);
$_month = substr($today, 5,2);
$_day = substr($today, 8, 2);
echo $_year." ".$_month;
回答5:
You can use it as
$today = date("Y/m/d");
$today = explode("/", $today);
$year = $today[0];
$month = $today[1];
$day = $today[2];
echo $year . ' ' . $month .' '. $day; // 2015 05 05
回答6:
substr()
doesn't work asyou think
You're thinking of :
string substr ( string $string , int $start , int $end )
But it is :
string substr ( string $string , int $start , [int $length)
So use substr($today,5,2)
for month and substr($today,7,2)
for day
来源:https://stackoverflow.com/questions/30051238/substr-is-not-working-as-expected