在PHP中如何将字符串转换为日期?

时间:2012-03-10 07:19:51

标签: php datetime

在C#中我可以做类似的事情:

string a = "03/12/2012";
            DateTime ab = DateTime.Parse(a);
            string b = DateTime.Now.ToShortDateString();
            DateTime c = Convert.ToDateTime(b);
            if(ab > c)
            {
                Console.WriteLine("tomorrow");
            }
            else
            {
                Console.WriteLine("Yesterday");
            }

            Console.ReadKey();

如何在PHP中执行此类操作? 我目前刚接触PHP,我还在研究它的大部分功能和特性。 先生/女士,你的答案将会有很大的帮助,非常感谢。谢谢++

2 个答案:

答案 0 :(得分:3)

$now = new DateTime;
$ab = DateTime::parseFromFormat($ab);

if ($ab > $now) {
  // Some time in the future
} else {
  // Some time in the past
}

等等。有关完整文档,请参阅manual关于date and time related functions and classes

答案 1 :(得分:0)

你可以尝试这个,我认为它可行,你在时间戳中转换字符串并将其与当前时间戳进行比较:

$a = strtotime("03/12/2012");
$b = time();
if (a > b) {
//Actually it could be tomorrow or later today or 10 years in the future...
  echo 'tomorrow';
}
else {
//The same as above... it could be yesterday or any date until 1970 (when UNIX timestamp begins)
  echo 'yesterday';
}