2015-11-07 107 views
1

我有日期女巫格式化d-m-y22-10-49我想将其转换为Date对象以将其保存在我的mysql数据库中。我尝试:在PHP中创建日期对象,以1970年之前的日期为特定格式

DateTime::createFromFormat('d-m-y', $mydate , new DateTimeZone('GMT')); 

但结果是2049-10-22而不是1949-10-22。我搜索了一下,得知那个createFromFormat只是在1970年之后才返回日期,但我不知道该怎么办。

P.s:22-10-49是我所拥有的,还有其他几个这样的日期,我无法更改它的格式或将它转换为22-10-1949或任何其他格式。 PS 2:“我用生日和excpect 22-10-15工作是1915年而不是2015年

+0

@Strawberry我没有得到它,你是什么意思? –

+0

@Strawberry 2015-10-22。 1970年前没有任何工作,日期假定在1970-2069范围内 –

+0

假设你有一个像22-10-15这样的值。你会期望实现1915年或2015年?如果答案是'我期望它是2015',那么哪一年是截止?难道只有超过'15'的任何值都指的是20世纪的一年 – Strawberry

回答

1

试试这个功能

编辑:首先,我们将转换两位数年份在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日

来源:Using strtotime for dates before 1970

+0

我其实从别的地方看过这个日期,我把它当成'22-10-49',我确定应该有另一种方式。我不想通过“if ... else”来更改我的日期格式。但谢谢你的回答 –

+0

@ShirinAbdolahi,日期格式修复每个日期你正在得到?即22-10-49,22-10-15,15-07-54等。 – Suyog

+0

是的,它是固定的@suyog –