Skip to content

Instantly share code, notes, and snippets.

@ring0li
Last active August 29, 2015 14:16
Show Gist options
  • Save ring0li/28764d2237bdf1c43fe8 to your computer and use it in GitHub Desktop.
Save ring0li/28764d2237bdf1c43fe8 to your computer and use it in GitHub Desktop.
php code
/**
*
* @param \DateTime $date DateTime object
* @param int $monthToAdd Months to add at time
*/
function addMonth(\DateTime $date, $monthToAdd)
{
$year = $date->format('Y');
$month = $date->format('n');
$day = $date->format('d');
$year += floor($monthToAdd / 12);
$monthToAdd = $monthToAdd % 12;
$month += $monthToAdd;
if ($month > 12) {
$year ++;
$month = $month % 12;
if ($month === 0) {
$month = 12;
}
}
if (! checkdate($month, $day, $year)) {
$newDate = \DateTime::createFromFormat('Y-n-j', $year . '-' . $month . '-1');
$newDate->modify('last day of');
} else {
$newDate = \DateTime::createFromFormat('Y-n-d', $year . '-' . $month . '-' . $day);
}
$newDate->setTime($date->format('H'), $date->format('i'), $date->format('s'));
return $newDate->format('Y-m-d');
}
echo addMonth(new \DateTime('2015-01-30'), 1); //2015-02-28
echo addMonth(new \DateTime('2015-01-30'), 2); //2015-03-30
echo addMonth(new \DateTime('2015-01-30'), 3); //2015-04-30
/**
* Export an array as downladable Excel CSV
* http://stackoverflow.com/questions/155097/microsoft-excel-mangles-diacritics-in-csv-files
* @param array $header
* @param array $data
* @param string $filename
*/
function toCSV($header, $data, $filename)
{
$sep = "\t";
$eol = "\n";
$csv = count($header) ? '"' . implode('"' . $sep . '"', $header) . '"' . $eol : '';
foreach ($data as $line) {
$csv .= '"' . implode('"' . $sep . '"', $line) . '"' . $eol;
}
$encoded_csv = mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $filename . '.csv"');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . strlen($encoded_csv));
echo chr(255) . chr(254) . $encoded_csv;
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment