16

I have date in this format (YYYYMM):

201201  // Gen, 2012
201202  // Feb, 2012
201203  // ecc

Let's say from 201203 I want to subtract 4 months. I can't do 201203 - 4 because it's = 201199

201203 - 4 should output 201111 (Nov, 2011)

Maybe i should convert my string to a date and then pass it to strtotime with -4 month?

Any suggest ?

8 Answers8

38

You can use strtotime in PHP:

$date = strtotime('2012-05-01 -4 months');

This article will help you.

Community
  • 1
  • 1
pearcoding
  • 1,149
  • 1
  • 9
  • 28
9

strtotime() can do it but you will need to add a day of the month for it to parse the date:

$input = '201203';

$input .= '01';

$date = strtotime($input .' -4 months');

echo date('Ym', $date);

Outputs Nov 2011:

201111
MrCode
  • 63,975
  • 10
  • 90
  • 112
8

Apart from the strtotime versions, since PHP 5.3 you can also use DateTime and DateInterval:

$date = DateTime::createFromFormat("Ym", "201201");
$interval = new DateInterval("P4M"); // 4 months
$fourMonthsEarlier = $date->sub($interval);
echo $fourMonthsEarlier->format("Ym");
Jon
  • 428,835
  • 81
  • 738
  • 806
2

Final_date = Currentdate - 4 months

<?php
$current_date = date("Y-m-d");

$final_date = date("Y-m-d", strtotime($current_date." -4 months"));

echo $final_date;
Kiran Reddy
  • 734
  • 12
  • 28
1

for EX $da=2014-04-01

if u want to minus 6 months use this..

$date = strtotime($da .' -4 months');
$final=date('Y-m-d', $date);

echo $final;

0

You can use strtotime to convert the string to a UNIX timestamp, which is in seconds. time() will give you the current UNIX timestamp. Subtract them to get how old the date is in seconds, and divide by 60*60*24 to get it in days

Norse
  • 5,674
  • 16
  • 50
  • 86
0

Previous code not working:

$da='2014-08-29';
$date = strtotime($da .' -6 months');
$final=date('Y-m-d', $date);
echo $final;
$date = strtotime($da .' -7 months');
$final=date('Y-m-d', $date);
echo $final;

February is missing!

-1
$date = '2016-09-01 00:00:00.000000';

$date2 = date("Y-m-d H:i:s.u", strtotime($date." -4 months"));

echo $date2; 

on run this code you will get 2016-05-01 00:00:00.000000

Nikolay Mihaylov
  • 3,868
  • 8
  • 27
  • 32