Php var per year and month

$date ='20101015';

how to convert to $year = 2010, $month = 10,$day =15

thank

+3
source share
3 answers

You can use the PHP substring function substras:

$year  = substr($date,0,4);  # extract 4 char starting at position 0.
$month = substr($date,4,2);  # extract 2 char starting at position 4.
$day   = substr($date,6);    # extract all char starting at position 6 till end.

If your source line as a leading or trailing space failed, then its best feed substrtruncated the input as. Therefore, before calling substr, you can do:

$date = trim($date);
+4
source

You can do everything in one go with

  • sscanf - Parses input from a string according to the format

Example:

list($y, $m, $d) = sscanf('20101015', '%4d%2d%2d');

or

sscanf('20101015', '%4d%2d%2d', $y, $m, $d);
+2
source

You can use the substring function

http://www.w3schools.com/php/func_string_substr.asp

$year=substr($date,0,4);
$month=substr($date,4,2);
$day=substr($date,6,2);
+1
source

Source: https://habr.com/ru/post/1769484/


All Articles