【问题标题】:Create Date object in PHP for dates before 1970 in certain format在 PHP 中以特定格式为 1970 年之前的日期创建 Date 对象
【发布时间】:2016-02-08 10:32:49
【问题描述】:

我的日期女巫被格式化为d-m-y 就像22-10-49 我想将其转换为日期对象以将其保存在我的 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 年。

【问题讨论】:

  • @Strawberry 没听懂,什么意思?
  • @Strawberry 2015-10-22。 1970 年之前没有任何工作,日期假定在 1970-2069 范围内
  • 假设你有一个像 22-10-15 这样的值。你认为这会在 1915 年或 2015 年实现吗?如果答案是“我希望它是 2015 年”,那么截止日期是哪一年?是不是简单地说,任何大于 '15' 的值都指的是 20 世纪的一年
  • 实际上我正在处理生日,所以我希望它是 1915 年,因为我的数据库 ID 中没有人出生于 2015 年。解决方案是什么? @草莓
  • 现在用您刚刚透露的重要见解编辑您的问题。

标签: php mysql date datetime


【解决方案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

【讨论】:

  • 我实际上是从其他地方读到这个日期的,我把它写成22-10-49,我确定应该有另一种方式。我不想通过if...elsees 更改我的日期格式。不过谢谢你的回答
  • @ShirinAbdolahi,您获得的每个日期的日期格式是否都已修复?即 22-10-49、22-10-15、15-07-54 等
  • 谢谢,它成功了,但第一部分是不必要的,我只是在 $date_part[2] 中添加了 '19' ,我认为没有更好的解决方案。谢谢
猜你喜欢
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 2011-07-02
  • 1970-01-01
  • 2017-04-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多