I would like to change the date format in the following code:
#search for all event start dates
$starts = $sxml->xpath('//event/startdate');
#get the unique start dates of these event
$dates = array_unique($starts);
foreach($dates as $date) {
echo "<li class='header'><h1>{$date}</h1></li>" ."\n";
currently, it pulls from an XML feed as 25/11/2021 and I would like to show it as Thursday 25 November 2021 - probably as multiple variables. However, date() is not working.
Any help is appreciated!
CodePudding user response:
Using the DateTime object it can be easy and accurate
$dates = ['25/11/2021','24/11/2021','23/11/2021'];
foreach ( $dates as $date){
$df = (DateTime::CreateFromFormat('d/m/Y', $date))->format('l d F Y');
echo "<li class='header'><h1>{$df}</h1></li>" ."\n";
}
RESULTS
<li class='header'><h1>Thursday 25 November 2021</h1></li>
<li class='header'><h1>Wednesday 24 November 2021</h1></li>
<li class='header'><h1>Tuesday 23 November 2021</h1></li>
CodePudding user response:
use date_format
date_format(DateTimeInterface $object, string $format): string
Note:
According to doc : date_format()
is not supported for dd/mm/YY date format
l: Sunday through Saturday
j: Day of the month(1 to 31)
F: January through December
Y: 4-digits years
$dates = ['2021/2/11','2021/12/12'];
foreach($dates as $date) {
$d = date_format(date_create($date),'l j F Y');
echo "<li class='header'><h1>${d}</h1></li>" ."\n";
}
OUTPUT
<li class='header'><h1>Thursday 11 February 2021</h1></li>
<li class='header'><h1>Sunday 12 December 2021</h1></li>