php 当前日期减去 4 个月?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10633879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Current date minus 4 month?
提问by pearcoding
I have date in this format (YYYYMM):
我有这种格式的日期(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 - 4because it's = 201199
假设我想从 201203 减去 4 个月。我做不到,201203 - 4因为它是 =201199
201203 - 4should output 201111(Nov, 2011)
201203 - 4应该输出201111(2011 年 11 月)
Maybe i should convert my string to a date and then pass it to strtotime with -4 month?
也许我应该将我的字符串转换为日期,然后将它传递给 -4 个月的 strtotime?
Any suggest ?
任何建议?
回答by pearcoding
回答by MrCode
strtotime()can do it but you will need to add a day of the month for it to parse the date:
strtotime()可以做到,但您需要添加一个月中的某一天来解析日期:
$input = '201203';
$input .= '01';
$date = strtotime($input .' -4 months');
echo date('Ym', $date);
Outputs Nov 2011:
2011 年 11 月的产出:
201111
回答by Jon
Apart from the strtotimeversions, since PHP 5.3 you can also use DateTimeand DateInterval:
除了strtotime版本之外,从 PHP 5.3 开始,您还可以使用DateTime和DateInterval:
$date = DateTime::createFromFormat("Ym", "201201");
$interval = new DateInterval("P4M"); // 4 months
$fourMonthsEarlier = $date->sub($interval);
echo $fourMonthsEarlier->format("Ym");
回答by Kiran Reddy
Final_date = Currentdate - 4 months
Final_date = 当前日期 - 4 个月
<?php
$current_date = date("Y-m-d");
$final_date = date("Y-m-d", strtotime($current_date." -4 months"));
echo $final_date;
回答by Norse
You can use strtotimeto 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*24to get it in days
您可以使用strtotime将字符串转换为 UNIX 时间戳,以秒为单位。time()将为您提供当前的 UNIX 时间戳。减去它们以获得以秒为单位的日期,然后除以60*60*24以天为单位
回答by Norse
for EX $da=2014-04-01
对于 EX $da=2014-04-01
if u want to minus 6 months use this..
如果你想减 6 个月使用这个..
$date = strtotime($da .' -4 months');
$final=date('Y-m-d', $date);
echo $final;
回声 $final;
回答by Bogdan Mantescu
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!
二月不见了!
回答by Gaurav Dixit
$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
在运行此代码时,您将获得 2016-05-01 00:00:00.000000

