转换此格式的日期';031012';转换为一个我可以添加天数的日期


convert a date in this format '031012' into a date that I can add days to

我有一个格式为030512(ddmmyy)的日期
但我在将其转换为可以添加天数的日期可用格式时遇到了问题。

基本上。。我从一个文本文件中提取了上面的日期,现在我需要能够添加一些天数。但我在解析这种格式的日期时遇到了问题。

有没有其他方法可以做到这一点,而不是像这样:

// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
$date_after = $day . "-" . $month . "-".$year;
// Now i need to add x days to this
$total_no_nights = 010; // must be this format
$days_to_add = ltrim($total_no_nights,"0"); // 10, remove leading zero
// how do i add 10 days to this date.

您可以这样做(php>=5.3):

$date = DateTime::createFromFormat('dmy', '030512');
$date->modify('+1 day');
echo $date->format('Y-m-d');

http://www.php.net/manual/en/datetime.createfromformat.php

对于php<5.3:

$dateArray = str_split('030512', 2);
$dateArray[2] += 2000;
echo date("d/m/Y", strtotime('+1 day', strtotime(implode('-', array_reverse($dateArray)))));

使用您已经拥有的月/日/年来尝试此操作:

$date = "$month/$day/$year";
$change = '+10 day';
echo date("d/m/Y", strtotime($change, strtotime($date)));

假设日期总是在未来(或者至少在2000年1月1日之后),那么您就大错特错了:

// I have a date in this format
$date = '030512'; // 03 May 2012
$day = substr($date,0,2);
$month = substr($date, 2,2);
$year = substr($date, 4,2);
// dd-mm-yy is not a universal format but we can use mktime which also gives us a timestamp to use for manipulation
$date_after = mktime( 0, 0, 0, $month, $day, $year );
// Now i need to add x days to this
$total_no_nights = "010"; // must be this format
$days_to_add = intval( $total_no_nights ); // No need to use ltrim
// Here's the "magic". Again it returns a timestamp
$new_date = strtotime( "+$days_to_add days", $date_after );

使用DateTime对象会更容易,但你说你不在PHP5.3上。

不能用字符串进行日期操作,因为它们不是日期。在PHP中,您可以使用Unix时间戳(实际上是整数…)或DateTime对象。在您的情况下:

$timestamp = strtotime('-10 days', mktime(0, 0, 0, $month, $day, $year));
echo date('r', $timestamp);

或:

$object = new DateTime("$year-$month-$day");
$object->modify('-10 days');
echo $object->format('r');

另外,请注意,010是一个八进制数,与十进制的8相对应。

使用sql中的convert函数,可以以适当的格式获取日期。

可以在php中执行操作来操作日期。我希望这能回答你的疑问。