Viral Bhoot
Viral Bhoot

Reputation: 357

Get date string only from an array containing a datetime string

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));

Upvotes: 3

Views: 9537

Answers (6)

Peter
Peter

Reputation: 9143

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:

Upvotes: 1

Tristup
Tristup

Reputation: 3673

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.

Upvotes: 2

AnkiiG
AnkiiG

Reputation: 3488

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]));

Upvotes: 2

Nirnae
Nirnae

Reputation: 1345

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

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

Upvotes: 1

Samir Selia
Samir Selia

Reputation: 7065

strtotime takes input as STRING.

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

Upvotes: 2

Andrius
Andrius

Reputation: 5939

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.

Upvotes: 5

Related Questions