在PHP中以某种格式在1970年之前的日期中创建Date对象 [英] Create Date object in PHP for dates before 1970 in certain format

查看:63
本文介绍了在PHP中以某种格式在1970年之前的日期中创建Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有日期巫婆,其格式如22-10-49一样,已格式化为d-m-y,我想将其转换为Date对象,以将其保存在mysql数据库中.我尝试:

I have date witch is formatted d-m-y like 22-10-49 I want to convert it to Date object to save it in my mysql Database. I try :

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

,但结果是2049-10-22而不是1949-10-22.我搜索后发现createFromFormat仅返回1970年之后的日期.但是我不知道该怎么办.

but the result is 2049-10-22 instead of 1949-10-22. I searched and got that createFromFormat only returns date after 1970. but I don't know what to do.

P.s:我有22-10-49,还有其他类似的日期,我无法更改其格式或将其转换为22-10-1949或任何其他格式. P.S 2:我正在过生日,我希望22-10-15是1915年而不是2015年.

P.s: 22-10-49 is what I have, and there are several other dates like this, I cannot change the format of it or convert it to 22-10-1949 or any other formats. P.S 2 : "I'm working with birthdays and excpect 22-10-15 to be 1915 rather than 2015.

推荐答案

尝试使用此功能.

编辑:首先,我们将两位数字年份转换为4位数字.然后,我们将形成完整的日期并将其传递给函数.

First we will convert two digit year in 4 digit. Then we will form complete date and pass it to function.

 $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

Output: 1949-10-22

来源:在1970年之前的日期中使用strtotime

这篇关于在PHP中以某种格式在1970年之前的日期中创建Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆