9
$date = date_create('2013-10-27');// This is the date that inputed in textbox and that format is (Y-m-d)

$date = date_create('2013-10-10');// and if i click the button i want to force change the 27 to 10?

我应该使用 date_modify 并做一些循环,还是有其他方法可以轻松地更改它而不是循环。

4

5 回答 5

45
$in = date_create('2013-10-27');

// example 1
$out = date_create($in->format('Y-m-10'));
echo $out->format('Y-m-d') . "\n";

// example 2
$out = clone $in;
$out->setDate($out->format('Y'), $out->format('m'), 10);
echo $out->format('Y-m-d') . "\n";

// example 3
$out = clone $in;
$out->modify((10 - $out->format('d')) . ' day');
echo $out->format('Y-m-d') . "\n";

演示

于 2013-10-03T07:49:50.113 回答
3

您可以使用原生 PHPdate_date_set ”函数进行此更改。

$date = date_create('2013-10-27');
echo $date->format('Y-m-d');
2013-10-27
date_date_set($date,
              date_format($date, 'Y'),
              date_format($date, 'm'),
              10);
echo $date->format('Y-m-d');
2013-10-10

或者使用面向对象的风格:

$date = new DateTime('2013-10-27');
echo $date->format('Y-m-d');
2013-10-27
$date->setDate($date->format('Y'), $date->format('m'), 10);
echo $date->format('Y-m-d');
2013-10-10
于 2017-01-22T19:15:36.783 回答
-2

$date = date("Y-m-d", strtotime("2013-10-10"));

更新:强制将日期从 27 更改为 10

1) 获取年份和月份

$date = date("Y-m-", strtotime( $_POST['user_selected_date'] ));

2) 追加你的一天

$date .= '10';

您也可以一步完成 $date = date("Y-m-10", strtotime( $_POST['user_selected_date'] ));

于 2013-10-03T02:58:36.437 回答
-3

注意:如果您只是想修改<input>来自<form>. 您可以尝试以下步骤:

$date = '2013-10-27'; // pass the value of input first.

$date = explode('-', $date); // explode to get array of YY-MM-DD

//formatted results of array would be
$date[0] = '2013'; // YY
$date[1] = '10';   // MM
$date[2] = '17';   // DD

// when trigger a button to change the day value.

$date[2] = '10'; // this would change the previous value of DD/Day to this one. Or input any value you want to execute when the button is triggered

// then implode the array again for datetime format.

$date = implode('-', $date); // that will output '2013-10-10'.

// lastly create date format

$date = date_create($date);
于 2013-10-03T03:14:20.297 回答
-4

使用 PCRE 函数

$date = '2013-10-27';
$new_date = preg_replace("/\d{2}$/", "10", $date);

preg_replace 手册

于 2013-10-03T04:37:02.857 回答