-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add DateFormat
function
#24
Conversation
<details> | ||
<summary>Supported Formats:</summary> | ||
|
||
<table><thead><tr><th></th><th>Format</th><th><code>2021-01-01 09:00:00</code></th><th>Description</th></tr></thead><tbody> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The code for generating the support table:
<?php
declare(strict_types=1);
use Illuminate\Database\Schema\Grammars\SQLiteGrammar;
use Tpetry\QueryExpressions\Function\Date\DateFormat;
use Tpetry\QueryExpressions\Tests\TestCase;
$_ENV['DB_CONNECTION'] = 'sqlite';
$_ENV['DB_DATABASE'] = ':memory:';
$groups = [
'Day' => [
'd' => 'Day of the month, 2 digits with leading zeros (01 to 31)',
'D' => 'A textual representation of a day, three letters (Mon through Sun)',
'j' => 'Day of the month without leading zeros (1 to 31)',
'l' => 'A full textual representation of the day of the week (Sunday through Saturday)',
'N' => 'ISO 8601 numeric representation of the day of the week (1 for Monday through 7 for Sunday)',
'S' => 'English ordinal suffix for the day of the month, 2 characters (st, nd, rd or th. Works well with j)',
'w' => 'Numeric representation of the day of the week (0 for Sunday through 6 for Saturday)',
'z' => 'The day of the year (starting from 0) (0 through 365)',
],
'Week' => [
'W' => 'ISO 8601 week number of year, weeks starting on Monday (Example: 42 - the 42nd week in the year)',
],
'Month' => [
'F' => 'A full textual representation of a month, such as January or March (January through December)',
'm' => 'Numeric representation of a month, with leading zeros (01 through 12)',
'M' => 'A short textual representation of a month, three letters (Jan through Dec)',
'n' => 'Numeric representation of a month, without leading zeros (1 through 12)',
't' => 'Number of days in the given month (28 through 31)',
],
'Year' => [
'L' => 'Whether it\'s a leap year (1 if it is a leap year, 0 otherwise)',
'o' => 'ISO 8601 week-numbering year. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (Examples: 1999 or 2003)',
'X' => 'An expanded full numeric representation of a year, at least 4 digits, with - for years BCE, and + for years CE. (Examples: -0055, +0787, +1999, +10191)',
'x' => 'An expanded full numeric representation if required, or a standard full numeral representation if possible (like Y). At least four digits. Years BCE are prefixed with a -, years beyond (and including) 10000 are prefixed by a +. (Examples: -0055, 0787, 1999, +10191)',
'Y' => 'A full numeric representation of a year, at least 4 digits, with - for years BCE. (Examples: -0055, 0787, 1999, 2003, 10191)',
'y' => 'A two digit representation of a year (Examples: 99 or 03)',
],
'Time' => [
'a' => 'Lowercase Ante meridiem and Post meridiem (am or pm)',
'A' => 'Uppercase Ante meridiem and Post meridiem (AM or PM)',
'B' => 'Swatch Internet time (000 through 999)',
'g' => '12-hour format of an hour without leading zeros (1 through 12)',
'G' => '24-hour format of an hour without leading zeros (0 through 23)',
'h' => '12-hour format of an hour with leading zeros (01 through 12)',
'H' => '24-hour format of an hour with leading zeros (00 through 23)',
'i' => 'Minutes with leading zeros (00 to 59)',
's' => 'Seconds with leading zeros (00 through 59)',
'u' => 'Microseconds. Note that date() will always generate 000000 since it takes an int parameter, whereas DateTime::format() does support microseconds if DateTime was created with microseconds. (Example: 654321)',
'v' => 'Milliseconds. Same note applies as for u. (Example: 654)',
],
'Timezone' => [
'e' => 'Timezone identifier (Examples: UTC, GMT, Atlantic/Azores)',
'I' => 'Whether or not the date is in daylight saving time (1 if Daylight Saving Time, 0 otherwise)',
'O' => 'Difference to Greenwich time (GMT) without colon between hours and minutes (Example: +0200)',
'P' => 'Difference to Greenwich time (GMT) with colon between hours and minutes (Example: +02:00)',
'p' => 'The same as P, but returns Z instead of +00:00 (available as of PHP 8.0.0) (Examples: Z or +02:00)',
'T' => 'Timezone abbreviation, if known; otherwise the GMT offset. (Examples: EST, MDT, +05)',
'Z' => 'Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. (-43200 through 50400)',
],
'Full Date/Time' => [
'c' => 'ISO 8601 date (2004-02-12T15:19:21+00:00)',
'r' => 'RFC 2822/RFC 5322 formatted date (Example: Thu, 21 Dec 2000 16:01:07 +0200)',
'U' => 'Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)',
],
];
$output = "<table><thead><tr><th></th><th>Format</th><th><code>2021-01-01 09:00:00</code></th><th>Description</th></tr></thead><tbody>\n";
uses(
TestCase::class,
);
it('generate markdown', function () use ($groups, &$output) {
$date = new DateTime('2021-01-01 09:00:00');
foreach ($groups as $groupName => $dateFormats) {
$dateFormats = array_filter(
$dateFormats,
function ($character) {
try {
(new DateFormat('column', $character))
->getValue(
new SqliteGrammar
);
} catch (Exception $e) {
return false;
}
return true;
},
ARRAY_FILTER_USE_KEY
);
$groupRowCount = count($dateFormats);
$firstRow = true;
foreach ($dateFormats as $character => $description) {
$output .= '<tr>';
if ($firstRow) {
$output .= "<td rowspan='{$groupRowCount}'>{$groupName}</td>";
$firstRow = false;
}
$result = $date->format($character);
$output .= "<td><code>{$character}</code></td>";
$output .= "<td><code>{$result}</code></td>";
$output .= "<td>{$description}</td>";
$output .= "</tr>\n";
}
}
$output .= '</tbody></table>';
file_put_contents(__DIR__.'/pest-markdown.md', $output);
})
->expectNotToPerformAssertions();
Wow, thats serious Effort. Kudos to that! As I've declared the package If there won't be any issues or problems we can merge it after some time. |
Thank you @tpetry 🙏 .. Congrats on the 1.0.0 release and can't wait for your Laracon talk :D
That's already the case, one array for all the formats, another array with and multiple dates ranged between (1970-2037) where I initiate a $testFormats = [
'\yy',
'a j-n-o F w W g G h H i s',
'Y-m-d\TH:i:s',
'a',
'A',
'd',
// .....
// .....
];
$testDates = [
'1970-01-01 00:00:00',
// .....
// .....
'2037-12-31 23:59:59',
];
expect(
$value = DB::table($table)->selectRaw(
new DateFormat('created_at', $format)
)->value('created_at')
)->toEqual(
$expected = (new DateTime($date))->format($format),
Take your time 🙏.. will let you know when it will be released as a separate package. |
This PR introduces a new
DateFormat
class that allows for formatting date columns using PHP's date format syntax.The foundations laid and discussed in #18, my apologies for the delayed submission. Considering the size of this PR, it's totally understandable if there is a preference for making this a separate package.
Functionality:
The
DateFormat
class takes a date column and a format string (likeY-m-d
) and splits it into individual characters (Y
,-
,m
, etc.).The
DirectDateFormatTrait
andEmulatedDateFormatTrait
traits manage the mapping of these format characters to SQL queries. Characters mapping directly to an SQL format (like%Y
forY
in MySQL) are used directly. Otherwise, an emulation function or the character as a literal/escaped is used.String Concatenation: This optimizes the format function call by combining adjacent string elements in the format array. For instance,
%Y, -, %m, -, %d
turns into%Y-%m-%d
. This results in a singleDATE_FORMAT(created_at, '%Y-%m-%d')
call instead of multiple individual calls.Special Handling:
Escaped Characters: Behaving like PHP's date format function, escaped characters (prefixed with
\
) are output as-is.Literal Handling in SQL Server: SQL Server returns null for calls like
FORMAT(column, '-')
. This behavior is different from other databases and is handled correctly here.Both escaped characters and literal handling in SQL Server utilize
$grammar->quoteString
instead of$grammar->escape
, since theescape
function requires a DB connection hit.Testing:
Tests cover common use cases and a generic test for each format character. The DateFormat class's output is matched against PHP's date function output, a more dynamic approach than the previous hardcoded test values in earlier PRs.
README:
Supported Formats:
2021-01-01 09:00:00
d
01
D
Fri
j
1
l
Friday
w
5
W
53
F
January
m
01
M
Jan
n
1
t
31
o
2020
Y
2021
y
21
a
am
A
AM
g
9
G
9
h
09
H
09
i
00
s
00
U
1609491600