Converting birthday in format DDMMMYY to date value in PHP

天大地大妈咪最大 提交于 2019-12-12 10:15:29

问题


I've got bunch of birthdays which are stored in format DDMMMYY. I need to convert those to date values, so i can store those in database.

Is there any easy way of telling strtotime function that date must be in the past?

<?php
$datestring = '22SEP41';
echo date('Y-m-d',strtotime($datestring)); //outputs 2041-09-22, should be 1941-09-22
?>

回答1:


<?php
$datestring = '22SEP41';

$matches = [];
preg_match('/([0-9]{2})([A-Z]{3})([0-9]{2})/', $datestring, $matches);

$prefix = ($matches[3] <= date('y') ? '20' : '19');

$matches[3] = "{$prefix}{$matches[3]}";

$ts = strtotime("{$matches[1]} {$matches[2]} {$matches[3]}");

// date ('Y-m-d', $ts) == 1941-09-22

This assumes that 22SEP06 should be interpreted as 2006 rather than 1906 - basically it gives the output a range of 1917 -> 2016.




回答2:


This method create a date of past century only if standard evaluated date is after today:

$date = date_create( $datestring );
if( $date->diff( date_create() )->invert )
{
    $date->modify( '-100 years' );
}
echo $date->format( 'Y-m-d' );

For

$datestring = '22SEP41';

the output is:

1941-09-22

For

$datestring = '22SEP01';

the output is:

2001-09-22

eval.in demo

Basically, we create a DateTime based on given string, then we calculate difference with current day; if the difference is negative (->invert), we subtract 1 century from the date.

You can personalize the condition using ->format('%R%Y') instead of ->invert. In this example:

if( $date->diff( date_create() )->format('%R%Y') < 10 )

Dates from 00 through 05 as evaluated as 2000-2005.




回答3:


You could try something like:

$ds = '22SEP41';

$day = $ds[0].$ds[1];

// Getting the month.
$mon = array(
  'JAN' => 1,
  'FEB' => 2,
  'MAR' => 3,
  'APR' => 4,
  'MAY' => 5,
  'JUN' => 6,
  'JUL' => 7,
  'AUG' => 8,
  'SEP' => 9,
  'OCT' => 10,
  'NOV' => 11,
  'DEC' => 12
);

$mont = $ds[2].$ds[3].$ds[4];
$month = $mon[$mont]; // Gets the month real.

$year = '19'.$ds[5].$ds[6];

$final = $day.'-'.$month.'-'.$year;

I tested it on my local machine and it worked. Hope it works and is what you're looking for :)



来源:https://stackoverflow.com/questions/36572264/converting-birthday-in-format-ddmmmyy-to-date-value-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!