如何在php中更改日期时间的日期

Den*_*ark 8 php datetime loops date

$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?
Run Code Online (Sandbox Code Playgroud)

我应该使用date_modify并进行一些循环,还是以其他方式以简单的方式更改它而不是循环.

Gla*_*vić 36

explode,implode,date,strtotime,preg_replace等真的吗?
OP正在使用DateTime类,不需要使用这种bisare解决方案降级他的代码.

$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";
Run Code Online (Sandbox Code Playgroud)

演示.

  • 这是我正在寻找的答案.不知道为什么OP选择另一个. (5认同)

Jho*_* H. -2

注意:如果您只是尝试修改<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);
Run Code Online (Sandbox Code Playgroud)

  • 这是荒唐的。OP已经在使用DateTime,它非常能够提供一个很好的解决方案。请参阅[Galvic的回答](http://stackoverflow.com/a/19153668/212940)。 (13认同)