i store a date information as week into my SQL database table as a varchar. Example: 2022-W10 I want to have the quarter out of this week. Which is in my example Quarter 1 Year 2022. Is there any possibility in PHP? I have not found anything on the PHP date() documentation for this.
CodePudding user response:
A date object can be created directly from a string such as '2022-W10' and the month can be determined using the format method. The calculation of the quarter is then just some school math.
$dateFromDb = '2022-W10';
$month = date_create($dateFromDb)->format('n');
$quarter = (int)(($month 2)/3); //int(1)
If the year is also required, this solution is available:
$dateFromDb = '2022-W49';
$dateTime = date_create($dateFromDb);
$quarter = (int)(($dateTime->format('n') 2)/3);
echo 'Quarter '.$quarter.' Year '.$dateTime->format('Y');
CodePudding user response:
I mean this problem can be solved by next steps:
<?php
$date = '2022-W10';
// 1. parce year & week from string
preg_match('/(\d{4})-W(\d )/', $date, $matches);
$year = $matches[1];
$week_no = $matches[2];
printf('Year: %d, Week no.: %d' . PHP_EOL, $year, $week_no);
// 2. create date by year & week number
$week_start = new DateTime();
$week_start->setISODate($year, $week_no);
// 3. get month number from date
$month = $week_start->format('n');
printf('Month: %d' . PHP_EOL, $month);
// 4. get quarter
$quarter = ceil($month/3);
printf('Quarter: %d' . PHP_EOL, $quarter);