• 4

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191


File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 191
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

So if today was April 12, 2010 it should return October 1, 2009

Some possible solutions I've googled seem overly complex, any suggestions?

Hm, maybe something like this;

echo date("F 1, Y", strtotime("-6 months"));


if you would like to specify a custom date use;

echo date("F, 1 Y", strtotime("-6 months", strtotime("Feb 2, 2010")));
  • 70
Reply Report

use a combination of mktime and date:

$date_half_a_year_ago = mktime(0, 0, 0, date('n')-6, 1, date('y'))

to make the new date relative to a given date and not today, call date with a second parameter

$given_timestamp = getSomeDate();
$date_half_a_year_ago = mktime(0, 0, 0, date('n', $given_timestamp)-6, 1, date('y', $given_timestamp))

to output it formatted, simply use date again:

echo date('F j, Y', $date_half_a_year_ago);
  • 9
Reply Report
    • I don't have PHP here to test this, but does mktime even accept negative months? It's documented as returning false for invalid arguments.
      • 1
    • @omg unicorns, yes, from the docs: »mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.«

It was discussed in comments but the accepted answer has some unneeded strtotime() calls. Can be simplified to:

date("F 1, Y", strtotime("Feb 2, 2010 - 6 months"));

Also, you can use DateTime() like this which I think is equally as readable:

(new DateTime('Feb 2, 2010'))->modify('-6 months')->format('M 1, Y');

Or using static method....

DateTime::createFromFormat('M j, Y','Feb 2, 2010')
    ->modify('-6 months')
    ->format('M 1, Y');
  • 2
Reply Report

Warm tip !!!

This article is reproduced from Stack Exchange / Stack Overflow, please click

Trending Tags

Related Questions