php - 以特定格式在 PHP 中为 1970 年之前的日期创建日期对象

标签 php mysql date datetime

我的日期女巫格式为 d-m-y,如 22-10-49 我想将其转换为 Date 对象以将其保存在我的 mysql 数据库中。我试试:

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 或任何其他格式。 P.S 2:“我正在处理生日,预计 22-10-15 是 1915 年而不是 2015 年。

最佳答案

试试这个函数。

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

 $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
}

Output: 1949-10-22

来源:Using strtotime for dates before 1970

关于php - 以特定格式在 PHP 中为 1970 年之前的日期创建日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33581012/

相关文章:

php - 在 Python 中使用 subprocess.run() 运行脚本,阻止所有文件读/写尝试

php - 从 PHP 对象中获取所有以子字符串开头的方法名称

PHP和Mysql(拉取信息)

mysql - 当使用 MySQL 定义的隐藏 ROW_ID 列作为 PK 时,哪些版本的 MySQL 会受到可伸缩性问题的影响?

php - 我如何知道连接日期(注册日期)的表日期列中不存在哪个月份?

algorithm - 营业时间分组算法

php - 根据字段值从不同表中取值

php - 从注册表查询后我的 session 自动销毁

asp.net - .NET 2.0 和 MySql 处于中等信任模式

python - 根据组的第一个日期将月份累积添加到日期列