3

I want to get only the date from an array containing a datetime string.

Array is:

print_r($incomplete); Output: Array ( [0] => 2015-09-21 11:20:37 ) 

And I want in below Format,

Array ( [0] => 2015-09-21 ) 

I have tried like this,

echo date('Y-m-d',strtotime($incomplete)); 
0

6 Answers 6

5

The date conversion code works. What you have in $incomplete is an array, so you will have to use $incomplete[0] to access that value. Easy solution for that would be this:

$incomplete[0] = date('Y-m-d',strtotime($incomplete[0])); 

Now you have the same array data without the time.

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

Comments

2

strtotime takes input as STRING.

echo date('Y-m-d',strtotime($incomplete[0])); 

Comments

2

strtotime expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp. And you have passed array to this function. Also add array index as below :

echo date('Y-m-d',strtotime($incomplete[0])); 

Comments

2

The date conversion will not work with the array directly. So you need to pass the array element in place of array in your code :

echo date('Y-m-d',strtotime($incomplete[0])); 

Hope this will help, please let me know if you need any help further.

Comments

1

You might want to target the cell of your array which contain the date like below :

echo date('Y-m-d',strtotime($incomplete[0])); 

1 Comment

Thank you all, but I want in array format as I mentioned in my question. Here, I am getting only date that I want but in array format.
1

Your conversion from Y-m-d H:i:s or datetime to date is fine. However you can't just execute that code on your array. You need to grab the specific array key-value pair.

Example

// Creating your array $array = array( '0' => '2015-09-20 10:20:30' ); // Get date from array and create DateTime Object $date = new DateTime($array[0]); // Change date format and output $array[0] = $date->format('Y-m-d'); 

On arrays

An array is a data structure that stores one or more similar type of values in a single value. For example if you want to store 100 numbers then instead of defining 100 variables its easy to define an array of 100 length.

There are three different kind of arrays and each array value is accessed using an ID c which is called array index. [...]

Resources:

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.