Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can force change the 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 loop or there's other way to change it in easy way rather than looping.

like image 497
Denmark Avatar asked Oct 03 '13 02:10

Denmark


2 Answers

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

like image 114
Glavić Avatar answered Sep 20 '22 20:09

Glavić


You can use the native PHP "date_date_set" function to make this change.

$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

Or using the Object-Oriented style:

$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
like image 33
Mario Rezende Avatar answered Sep 22 '22 20:09

Mario Rezende