How to make me change day in datetime in php

$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?

Should I use date_modify and do some kind of loop or is there another way to easily change it, not a loop.

+4
source share
5 answers

Note. If you are just trying to change the value of the day to day, coming from sent <input>from <form>. You can try the following steps:

$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);
+1
source

explode, implode, date, strtotime, preg_replace, Etc. Really?
OP uses a class DateTime, you don’t need to lower its code with this kind of bisare solution.

$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 .

+25
source

PHP " date_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
0

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

Updated: make me change the day from 27 to 10

1) get the year and month

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

2) add your day

$date .= '10';

You can also finish it in ONE step. $date = date("Y-m-10", strtotime( $_POST['user_selected_date'] ));

-one
source

Use PCRE function

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

preg_replace instruction

-one
source

All Articles