Skip to content

Instantly share code, notes, and snippets.

@jakeasmith
Last active December 20, 2018 13:59
Show Gist options
  • Save jakeasmith/5307825 to your computer and use it in GitHub Desktop.
Save jakeasmith/5307825 to your computer and use it in GitHub Desktop.
Get the timestamp for the beginning of the last quarter.
<?php
$start_date = strtotime('3 months ago');
$start_quarter = ceil(date('m', $start_date) / 3);
$start_month = ($start_quarter * 3) - 2;
$start_year = date('Y', $start_date);
$start_timestamp = mktime(0, 0, 0, $start_month, 1, $start_year);
echo $start_timestamp;
SELECT UNIX_TIMESTAMP(STR_TO_DATE(CONCAT('1,', ((QUARTER(DATE_SUB(NOW(), INTERVAL 3 MONTH)) * 3) - 2), ',', YEAR(NOW())),'%d,%m,%Y'))
@jakeasmith
Copy link
Author

Both of these work, but they seem overly complex. Do you know of any good functions or patterns that would make this a bit more concise and readable?

@jblossomweb
Copy link

when does the quarter start?

@jakeasmith
Copy link
Author

Wow. I blanked on this at first.

1 - January 1st
4 - April 1st
7 - July 1st
10 - October 1st

@jeffreyroberts
Copy link

ok, this code is mad tight, the only solutions I am coming up with involve switch/case statements, based on either the number representation of the month or the day, with ranges in the cases, and I see bugs with that, kudos to a hell of a job =]

@jakeasmith
Copy link
Author

lol! Thanks @jeffreyroberts.

@adamjimenez
Copy link

The sql one is incorrect I think as it appends the current year. So in January it will give you October 10th 2016 instead of 2015.

@ddsc01
Copy link

ddsc01 commented Mar 13, 2018

great idea.
i needed an end date of the quarter for a range.

if anybody is in need, try this:
$end_timestamp = strtotime('last day of '.date('F', strtotime("+2 month",strtotime(date('F',$start_timestamp)."1")))." {$start_year}");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment