在PHP中将mm / dd / yy转换为mm / dd / yyyy

时间:2010-07-15 00:40:08

标签: php regex date

我正在开发一个项目,要求我从文件中读取值并在将它们存储到别处之前稍微操作它们。我需要做的一件事是将一些日期从mm / dd / yy格式转换为mm / dd / yyyy格式。对我来说不幸的是,我对PHP和正则表达式相对较新(我认为这是解决这个问题的更好方法之一),因此我有些神秘。任何和所有帮助将不胜感激。谢谢!

4 个答案:

答案 0 :(得分:5)

PHP有built-in function strtotime()仅适用于此类任务......它甚至可以对此规则后的2位数年度进行最佳猜测: 00-之间的值69被映射到2000-2069和70-99到1970-1999 。一旦你有了PHP喜欢的UNIXy格式的日期/时间,那么你可以使用date() function将它打印出来。

<?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);
}
?>

(我认为我们在这里与时区无关,或者会增加并发症。)

答案 1 :(得分:2)

你可以尝试这个,它可能会或可能不会起作用:

$new_date = date( 'm/d/Y', strtotime( $old_date ) );

$old_date的格式与您所讨论的格式相同。

答案 2 :(得分:2)

这里的一个问题是YY,假设它是相对最新的,可以是19YY或20YY。这意味着你应该选择一个数字作为截止。我们称之为$cutOff如果YY小于$cutOff,我们希望20YY如果大于我们想要19YY

你可以用正则表达式来做,但由于你的例子很简单,正则表达式往往较慢,你可以简单地使用substrsubstr_replace进行字符串操作。

以下是如何更改字符串mm / dd / yy int mm / dd / yyyy:

<?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;
?>

答案 3 :(得分:0)

您可以将年份附加到两个值(19或20),如下所示:

//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
相关问题