1

I have a date time string 2018-12-05 03:05:43 How I convert it to array like this format:

[2018, 12, 5, 3, 5, 43]
1
  • 3
    date('Y'), date('m') etc. Commented Dec 14, 2018 at 7:10

3 Answers 3

4

You can parse the date using PHP's DateTime class and output each component separately:

$date = date_create_from_format('Y-m-d H:i:s', '2018-12-05 03:05:43');
$array = array(
    (int)$date->format('Y'),
    (int)$date->format('m'),
    (int)$date->format('d'),
    (int)$date->format('H'),
    (int)$date->format('i'),
    (int)$date->format('s')
    );
print_r($array);

Output:

Array ( 
    [0] => 2018
    [1] => 12
    [2] => 5
    [3] => 3
    [4] => 5
    [5] => 43
)

Demo on 3v4l.org

Sign up to request clarification or add additional context in comments.

Comments

3

You could use explode() and merge()

$tmp1 = explode(' ', '2018-12-05 03:05:43');
$tmp2 = explode('-', $tmp1[0]);
$tmp3 = explode(':', $tmp1[1]);

$merge = array_merge($tmp2, $tmp3); 

Comments

1

You can also use regex.

The pattern finds an optional zero and any digit(s).
The zero is not part of the capture thus will not be presented in the [1] array.

$str ="2018-12-05 03:05:43";

preg_match_all("/0*(\d+)/", $str, $arr);
$arr = $arr[1]; // only keep the capture
var_dump($arr);

Output:

array(6) {
  [0]=>
  string(4) "2018"
  [1]=>
  string(2) "12"
  [2]=>
  string(1) "5"
  [3]=>
  string(1) "3"
  [4]=>
  string(1) "5"
  [5]=>
  string(2) "43"
}

https://3v4l.org/1sGSR

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.