1

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.

  • 2
    Should the first day of the week determine the quarter? Keep in mind that some weeks might start in one quarter and end in another. – Hendrik Mar 15 '22 at 09:18
  • True this can happen. I guess the first day makes sense. Thank you for this hint. – Mischa Mustermann Mar 15 '22 at 09:19
  • Does this answer your question? [How to convert week number and year into unix timestamp?](https://stackoverflow.com/questions/5763340/how-to-convert-week-number-and-year-into-unix-timestamp) – Andrea Olivato Mar 15 '22 at 09:35
  • Once you have the date, [deducing the quarter](https://stackoverflow.com/questions/1234443/easy-way-to-get-day-number-of-current-quarter) should be immediate – Andrea Olivato Mar 15 '22 at 09:36

2 Answers2

2

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');  
jspit
  • 7,276
  • 1
  • 9
  • 17
0

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

Test PHP date conversion online

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39