我正在处理一个需要从文件中读取数据并在存储到其他地方之前稍微修改的项目。其中一件我需要做的事情是将某些日期从mm/dd/yy格式转换为mm/dd/yyyy格式。不幸的是,我对PHP和正则表达式(我认为这是解决这个问题的较好方法之一)相对较新,因此有些困惑。任何帮助都将不胜感激。谢谢!
PHP有一个内置函数strtotime()
,专门用于这种任务...它甚至可以根据以下规则猜测2位数的年份:00-69之间的值映射到2000-2069,70-99映射到1970-1999。一旦你有了PHP偏好的UNIX格式的日期/时间,那么你就可以使用date()
函数以任何你想要的方式打印它。
<?php
$str = '02/28/98';
// in PHP 5.1.0+, strtotime() returns false if it fails
// previous to PHP 5.1.0, you would compare with -1 instead of false
if (($timestamp = strtotime($str)) === false) {
echo "Couldn't figure out the date ($str)!";
} else {
echo "Reformatted date is " . date('m/d/Y', $timestamp);
}
?>
YY
是相对较新的,它可以是19YY或20YY。这意味着你应该选择一个数字作为分界线。让我们称其为$cutOff
。如果YY小于$cutOff
,我们要20YY
,如果大于我们要19YY
。<?php
// Our date
$str = "01/04/10";
$cutoff = 50;
// See what YY is
// Get the substring of $str starting two from the end (-2)... this is YY
$year = substr($str, -2);
// Check whether year added should be 19 or 20
if ($year < 50)
// PHP converts string to number nicely, so this is our 20YY
$year += 2000;
else
// This is 19YY
$year += 1900;
// Repace YY with YYYY
// This will take $str and replace the part two from the end (-2) undtil
// the end with $year.
$str = substr_replace($str, $year, -2);
// See what we got
echo $str;
?>
strtotimes()
使用“70”作为基准年份,或者您有早于1970年的日期,因为它们不适合UNIX自纪元以来经过的秒数日期。这种策略非常必要。 - ewall$new_date = date( 'm/d/Y', strtotime( $old_date ) );
$old_date
是您所讨论的格式。
//for $s_date = "yy-dd-mm"
if (substr($s_date,6,2) >= 50){
$standarddate = "19" . substr($s_date,6,2); //19yy
$standarddate .= "-" . substr($s_date,0,2); //mm
$standarddate .= "-" . substr($s_date,3,2); //dd
} else {
$standarddate = "20" . substr($s_date,6,2); //20yy
$standarddate .= "-" . substr($s_date,0,2); //mm
$standarddate .= "-" . substr($s_date,3,2); //dd
}
// you will get yyyy-mm-dd
12/22/78
这样的日期。通常通过设置一个值L
来解决这个问题,该值与两位数年份yy
进行比较;如果yy
大于L
,则四位数年份为19yy
;否则四位数年份为20yy
。 - apaderno