【问题标题】:How can force change the day in datetime in php如何在php中强制更改日期时间中的日期
【发布时间】:2013-10-03 02:56:04
【问题描述】:
$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 并做一些循环,还是有其他方法可以简单地更改它而不是循环。

【问题讨论】:

标签: php date loops datetime


【解决方案1】:
$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";

Demo.

【讨论】:

  • 这是我一直在寻找的答案。想知道为什么 OP 选择了另一个。
【解决方案2】:

您可以使用原生 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

【讨论】:

    【解决方案3】:

    $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'] ));

    【讨论】:

    • 如果不同月份呢?还是年份?
    • 请扩展您的答案以使其更有用。
    【解决方案4】:

    注意:如果您只是想从<form> 中修改来自已提交<input> 的日期的日期值。您可以尝试以下步骤:

    $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);
    

    【讨论】:

    • 这太荒谬了。 OP 已经在使用 DateTime ,它非常有能力提供一个很好的解决方案。见Galvic's answer
    【解决方案5】:

    使用 PCRE 函数

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

    preg_replace manual

    【讨论】:

    • 如果您使用的是正则表达式,您很可能做错了。就是这样。
    猜你喜欢
    • 1970-01-01
    • 2015-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2017-06-12
    • 1970-01-01
    相关资源
    最近更新 更多