-1

I'm having a lot of trouble and no success in adding 1 billion seconds to a DateTime object (user input variable).

The user enters their date of birth (DOB) in format YYYY-m-d H:i:s. This is then converted to DateTime(). Then 1 billion seconds are added to the DOB. The output is to be the DOB + 1 billion seconds, in format YYYY-m-d H:i:s.

I can not work out how to do this, and haven't found any suitable examples from other posts which have solved this issue.

Any help is welcome. Thanks

Martin Reilly
  • 21
  • 1
  • 3
  • 1
    What have you tried so far? There should be tons of examples out there to add a number of seconds to an existing `DateTime` instance – Nico Haase Jan 25 '19 at 14:28

3 Answers3

2

You can use DateTime::add function http://php.net/manual/en/datetime.add.php

$date = new DateTime(DOB);
$date->add(new DateInterval('PT1000000000S'));
echo $date->format('Y-m-d H:i:s') . "\n";
Jeremiah
  • 40
  • 3
0
echo date("Y-m-d H:i:s", (strtotime('1991-12-13 06:25:12') + 1000000000));

You can do it in one line of code. Convert your date using strtotime and add the seconds. It's weird to ask for H:i:s in a dob field though.

The output is 2023-08-21 09:11:52 (double checked also through here)

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
0

Man, I always hated doing datetime logic. In my experience the easiest way to do this is to convert everything to Unix timestamp. I integers are easier to manipulate than DateTime object (though this mentality could be a hold over from #backintheday).

Do your logic would be something similar to the following:

$dob = strtotime('2018-1-1 12:00:00');
echo $dob;
echo  "\n";
$sum = ($dob + 1000000000);
echo date('r', $sum);

That should get you heading the way you want.

*Note be sure your machine is 64 bit, else dates after 2039 won't work due to the limits of 32 bit integers.

David J Eddy
  • 1,999
  • 1
  • 19
  • 37