1

How to add a date with DateInterval for specified variable?

<?php
$begin = new DateTime('2010-01-01 08:00');
$end = new DateTime( '2010-01-05 20:00');

$interval = new DateInterval('P1D');
$period = new DatePeriod($begin, $interval, $end);

foreach ( $period as $dt ) {
  $tempBegin = $tempEnd = $dt;
  $tempEnd->add(new DateInterval('P1D'));

  echo $tempEnd->format( "Y-m-d H:i" ) . '<br/>';
  echo $tempBegin->format( "Y-m-d H:i" ) . '<br/>';
}

It will give result like this :

2010-01-02 08:00
2010-01-02 08:00
2010-01-03 08:00
2010-01-03 08:00
2010-01-04 08:00
2010-01-04 08:00
2010-01-05 08:00
2010-01-05 08:00
2010-01-06 08:00
2010-01-06 08:00

I want to add 1 day just for $tempBegin variable.

5
  • See stackoverflow.com/questions/2579458/… Commented Jun 19, 2014 at 23:41
  • Why does this question look so much like stackoverflow.com/q/24317227 ? Edit: Never mind, I see it was one of your answers; bizarro. Commented Jun 20, 2014 at 0:03
  • @Fred-ii- yeah, I'm trying to answer that question and struggling for this clone function for almost 40 minutes. I'm waiting for someone to answer that correctly but it make me hard to sleep if I can't split it out somehow. So I created different question with similar example. Is it against rules? Commented Jun 20, 2014 at 0:14
  • 1
    Some don't like it as they see it as points sharing/pushing. It's not against the rules, per se, yet some do use ghost accounts and ask the same question(s) over and over again; I've seen it happen myself and it does get annoying at times, because as coders, and am sure you can notice patterns as well, is that we notice the same piece of code traversing from one site to another. Code is like a fingerprint, well to me anyway. We don't mind helping but when it starts to be the same pattern, that's when someone starts flagging questions. I'm just trying to spare you the embarrassment. ;-) Commented Jun 20, 2014 at 0:18
  • @Fred-ii- I see, yeah.. tht's make sense to me, I didn't realize that in first place. I'll keep it in mind next time. Thank you. Commented Jun 20, 2014 at 0:23

1 Answer 1

3

When you assign objects, you don't make copies. So the variables $tempBegin and $tempEnd both refer to the same object, and when you modify it with add() it modifies the object that both variables refer to.

You need to clone the object:

$tempBegin = $dt;
$tempEnd = clone $tempBegin;
$tempEnd->add(new DateInterval('P1D'));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.