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 ?
asked May 17, 2012 at 10:22 4 You can use
strtotime in PHP: $date = strtotime('2012-05-01 -4 months');
This article will help you.
answered May 17, 2012 at 10:25 pearcodingpearcoding 1,1511 gold badge9 silver badges28 bronze badges 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
answered May 17, 2012 at 10:30 MrCodeMrCode 62.4k10 gold badges85 silver badges111 bronze badges 0 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");
answered May 17, 2012 at 10:35 JonJon 418k78 gold badges722 silver badges793 bronze badges 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;
answered Sep 4, 2018 at 11:36 Kiran ReddyKiran Reddy 70412 silver badges28 bronze badges 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; answered Apr 17, 2014 at 8:10 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 answered May 17, 2012 at 10:25
NorseNorse 5,53415 gold
badges48 silver badges86 bronze badges 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! answered
Aug 29, 2014 at 12:14 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 answered Sep 15, 2016 at 12:36
|