1

I'm building a CMS system using PHP for the first time. Part of this project involves me printing out a date from a column in my database using a loop. This is what the loop currently looks like:

<td><?php echo $record['fromDate']; ?> - <?php echo $record['toDate']; ?> | <?php echo $record['location']; ?></td>

The date is printing out like this: 2022-03-03 - 2022-03-23

What can I do to print it out as follows: 03 March 2022 - 23 March 2022

3 Answers3

1

To begin, this can be interpreted as PHP problem rather than SQL

You can use date_format() PHP function and format it with 'd F Y'while displaying with HTML

date_format(date_create('2000-01-01'), 'd F Y')
// 01 January 2000

As per docs

F - A full textual representation of a month, such as January or March


so your code would look like

<?php echo date_format(date_create($record['fromDate']), 'd F Y'); ?> - <?php echo date_format(date_create($record['toDate']), 'd F Y'); ?>
Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
0

As seen in the accepted answer to this similar post:

$originalDate = $record['fromDate']; //or $record['toDate']
$newDate = date("j F Y", strtotime($originalDate));

And use $newDate in your echo statement.

j is the day of the month (without leading zeros), F is the month name, and Y is the year.

date() php

eap314
  • 305
  • 1
  • 7
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 12 '22 at 03:27
0

Word of Warning: If you're not telling your program exactly how to parse a date, it's guessing.

At some point you're going to feed a date like 2022-03-04 into it and get a result that you're not expecting.

$date_str = '2022-03-03';
$dt = DateTime::createFromFormat('Y-m-d', $date_str)->format('d F Y');
var_dump($dt);

Output:

string(13) "03 March 2022"
Sammitch
  • 30,782
  • 7
  • 50
  • 77