I get the string in the form "1990-03-02" .
This, as you can see, is a date. How to divide this date into 3 parts so that it is:
$a = 1990; $b = 3; $c = 2; I get the string in the form "1990-03-02" .
This, as you can see, is a date. How to divide this date into 3 parts so that it is:
$a = 1990; $b = 3; $c = 2; Once you are working with a date, you can use specialized PHP tools to work with date / time, namely the class \DateTime . And you can do it like this:
$d = DateTime::createFromFormat('Ym-d', '1990-03-02'); $a = (int)$d->format('Y'); $b = (int)$d->format('j'); $c = (int)$d->format('n'); Working example on IDEOne.
Note :
For this particular task with splitting a string into three variables, the approach using \DateTime is somewhat redundant. However, it gives you, on the one hand, an incredible flexibility of formatting the result, and on the other, it allows you to think about the date as a date, and not as a set of three variables. All this, ultimately, allows you to increase the level of code abstraction and reduce its total complexity.
And yet, with this approach, you can easily get other parameters of your original date with zero labor costs. So, for example, you can get the number of the week:
$week = (int)$d->format('W'); Using a special data type for a date allows you to do more cool things using a clear high-level language. For example, you can add to your date an arbitrary interval , say, a week:
$new_date = $d->add(new DateInterval('P1W')); $d->add(new DateInterval('P1W')); - Sergiks 9:39 pmYou can use the sscanf() function to parse a formatted string:
$dateString = "1990-03-02"; list($a, $b, $c) = sscanf($dateString, "%d-%d-%d"); $ a = explode ('-', $ str); so get a split array. Well, at zero in front check every element of the array is not a problem ...
$str = "1990-03-02"; $a = explode('-', $str); $year = $a[0]; if($a[1][0]==0){$month = $a[1][1];}else{$month = $a[1];} if($a[2][0]==0){$day = $a[2][1];}else{$day = $a[2];} either ternary check
$str = "1990-03-02"; $a = explode('-', $str); $year = $a[0]; $a[1][0]==0 ? $month = $a[1][1] : $month = $a[1]; $a[2][0]==0 ? $day = $a[2][1] : $day = $a[2]; условие ? если_да : если_нет условие ? если_да : если_нет ? For example, $month = $a[1][0]==='0' ? $a[1][1] : $a[1]; $month = $a[1][0]==='0' ? $a[1][1] : $a[1]; - Sergiks list($a, $b, $c) = explode('-', '1990-03-02'); Source: https://ru.stackoverflow.com/questions/539893/
All Articles
explodeorstrtotimeand afterdate- Naumov