我有日期女巫的格式d-m-y
就像我想将其转换为日期对象以将其保存在我的mysql数据库中22-10-49
。我尝试:
DateTime::createFromFormat('d-m-y', $mydate , new DateTimeZone('GMT'));
但结果是2049-10-22
而不是1949-10-22
.我搜索并得到了createFromFormat
1970 年之后的唯一返回日期。但我不知道该怎么办。
PS:22-10-49
是我所拥有的,还有其他几个这样的日期,我无法更改它的格式或将其转换为22-10-1949
或任何其他格式。P.S 2:"我的工作是生日,22-10-15
是1915年而不是2015年。
试试这个函数。
编辑:首先,我们将以4位数字转换两位数的年份。然后我们将形成完整的日期并将其传递给函数。
$original_date = '22-10-49';
$date_part = explode('-',$original_date);
$baseyear = 1900; // range is 1900-2062
$shortyear = $date_part[2];
$year = 100 + $baseyear + ($shortyear - $baseyear) % 100;
$subdate = substr( $original_date, 0, strrpos( $original_date, '-' ) );
$string = $subdate."-".$year;
echo safe_strtotime($string);
function safe_strtotime($string)
{
if(!preg_match("/d{4}/", $string, $match)) return null; //year must be in YYYY form
$year = intval($match[0]);//converting the year to integer
if($year >= 1970) return date("Y-m-d", strtotime($string));//the year is after 1970 - no problems even for Windows
if(stristr(PHP_OS, "WIN") && !stristr(PHP_OS, "DARWIN")) //OS seems to be Windows, not Unix nor Mac
{
$diff = 1975 - $year;//calculating the difference between 1975 and the year
$new_year = $year + $diff;//year + diff = new_year will be for sure > 1970
$new_date = date("Y-m-d", strtotime(str_replace($year, $new_year, $string)));//replacing the year with the new_year, try strtotime, rendering the date
return str_replace($new_year, $year, $new_date);//returning the date with the correct year
}
return date("Y-m-d", strtotime($string));//do normal strtotime
}
产量 : 1949-10-22
资料来源:对1970年之前的日期使用strtotime