Home > Mobile >  Printing dates as strings in SQL
Printing dates as strings in SQL

Time:03-12

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

CodePudding user response:

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

CodePudding user response:

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"

CodePudding user response:

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

  • Related