php函数转换“;2012年4月5日“;至“;2012年5月4日


php function to convert "04-05-2012" to "04/05/2012?

我尝试过使用date("m/d/Y", strtotime("04-05-2012")),但我会得到"05/04/2012",或者在其他日期,例如"03-30-2012",我会得到"12/31/1969"(这很有意义,因为它混合了月份和日期,没有第30个月。那么我应该怎么做呢?我还想把值转换成UNIX时间,这样我就可以在MySQL数据库中搜索它了。

您可以使用DateTime对象和createFromFormat静态方法来完成它:

$date = DateTime::createFromFormat('m-d-Y',"03-30-2012");
$date->format('m/d/Y');

如果您确信您开始使用的格式是DD-MM-YYY,为什么不使用简单的替换呢?

例如$newDate = str_replace('-', '/', '04-05-2012');

一种方法是使用explode()mktime():

$inDate = '03-30-2012';
list($m, $d, $y) = explode('-', $inDate);
$outDate = date('m/d/Y', mktime(0, 0, 0, $m, $d, $y));

不过,这是假设格式在某种程度上是动态的。否则,正如其他人指出的那样,str_replace()是你最好的选择。

与其说这是一个日期格式问题,不如说是一个字符串操作问题。

但知道strtotime()的存在还是很好的。

[ghoti@pc ~]$ cat transdate.php 
#!/usr/local/bin/php
<?php
$olddate = "04-05-2012"; // assuming mm-dd-YYYY
// Get the date parts into an array
$parts = explode("-", $olddate);
// Switch to YYYY-mm-dd, which will be interpreted consistently
$neworder = sprintf("%s-%s-%s", $parts[2], $parts[0], $parts[1]);
printf("New order: %s'n", $neworder);
// Set your timezone, or PHP will whine and complain
date_default_timezone_set('America/Toronto');
// Convert your reordered date to an epoch second (unix timestamp)
$epoch = strtotime($neworder);
// At a terminal, `man strftime` (or read the PHP function's docs) for details.
print "Alternate formats:'n";
printf("'t%s'n", strftime("%D", $epoch));
printf("'t%s'n", strftime("%F", $epoch));
printf("'t%s'n", strftime("%A %B %e, %Y (week %U)", $epoch));
[ghoti@pc ~]$ ./transdate.php 
New order: 2012-04-05
Alternate formats:
        04/05/12
        2012-04-05
        Thursday April  5, 2012 (week 14)
[ghoti@pc ~]$ 

这将在PHP 5.1.6中工作。见鬼,除了date_default_timezone_set()之外,它应该在PHP4中工作。