This question already has an answer here:
I need to create a user function for date formatting from the defined input parameter inside my array. The array I have is looking like this..
$data[1]["Name"] = "Jack";
$data[1]["Job"] = "CEO";
$data[1]["Date"] = "2016-09-29";
$data[1]["Customer"] = "Yes";
$data[2]["Name"] = "Jane";
$data[2]["Job"] = "Manager";
$data[2]["Date"] = "2016-02-08";
$data[2]["Customer"] = "No";
and so it continues.. What I need to do is to create user function function date_trans()
which will change the date format to ('d.m.Y')
from the given format inside the array. The idea is to echo formatted dates from my array into a table using nested loops.
I've created the loop and the HTML table successfully, but can't figure out how to create a function for this. Note: For this exercise, it needs to be a function. Using strtotime
comes to my mind for this..
function date_trans()
{
//
}
How should I create this function?
</div>
Using function-call you can do it like below:-
<?php
$data[1]["Date"] = "2016-09-29";
function date_trans($date)
{
return date ('d.m.Y',strtotime($date));
}
echo $final_date = date_trans($data[1]["Date"]);
Now call this function inside foreach for dates only and pass the date as a parameter.
However in foreach directly you can do like below:-
echo date("d.m.Y", strtotime($your_date_in_array)); // no function call required
It is,
$formatted_date = date("d.m.Y", strtotime($your_date_in_array));
Thanks.
The function:
function date_trans($date) {
try {
$d = new DateTime($date);
} catch (Exception $e) {
trigger_error($e->getMessage());
return null;
}
return $d->format('d.m.Y');
}
Usage:
if ($d = date_trans("2016-09-29")) {
echo $d;
} else {
echo "failed to process date";
}