-4

I cannot use DateTime because of the version of PHP I am running. Can anyone suggest a way to get the equivalent value using strToTime or some other date function. I know this is probably an easy question but I am very rusty on dates in php.

i.e. something like

$date = strToTime('today');

where $date is a date that I can then manipulate by adding hours and so forth along these lines...

$start = $date->format('Y-m-d H:i:s');
$date->modify('+ 60 minutes');
$end = $date->format('Y-m-d H:i:s');

Thanks in advance for any suggestions.

user1904273
  • 4,562
  • 11
  • 45
  • 96
  • You realise that the version of PHP that you're running is several years out-of-date, and that you really should be upgrading it.... the latest version is PHP7, you must be running < 5.2.0 – Mark Baker Dec 14 '15 at 19:16
  • wrong. I am running 5.329. Know your php versions! – user1904273 Dec 14 '15 at 19:50
  • `The DateTime class ¶ (PHP 5 >= 5.2.0, PHP 7) ` Know your PHP versions.... and even 5.3.29 is over a year out of date now – Mark Baker Dec 14 '15 at 19:55
  • 1
    DateTime works find on PHP 5.3.29 - as does 'Carbon' so what exactly is the issue: Ok try: `$date = new \DateTime();` before your code: works fine here on PHP 5.3.29. Unlike the accepted answer - this works with your code, Which was correct. Whatever. Was just a comment ;) – Ryan Vincent Dec 14 '15 at 20:38
  • You are right. What caused the code to break was the missing \ although slapyo's answer was a good solution and strtotime is apparently benchmarked as faster than DateTime. However, why does the documentation not mention the \?. http://php.net/manual/en/datetime.construct.php – user1904273 Dec 14 '15 at 20:47
  • 1
    Please read about : [Namespaces overview](http://php.net/manual/en/language.namespaces.php). All of PHP after 5.3 uses `namespaces`. Also: [http://php.net/manual/en/language.namespaces.global.php](http://php.net/manual/en/language.namespaces.global.php). It is a useful thing - but it is easy to forget the '\' before names to indicate that it is a PHP `thing`. – Ryan Vincent Dec 14 '15 at 20:53

2 Answers2

2
$startTime = strtotime('now');
$endTime = strtotime('+60 minutes', $startTime);

$start = date('Y-m-d H:i:s', $startTime);
$end = date('Y-m-d H:i:s', $endTime);

You can pass a 2nd parameter to strtotime that will be the time that is used when the calculation is made. By default it is time().

strtotime

slapyo
  • 2,979
  • 1
  • 15
  • 24
0

There are alternatives, that you can get from github, just type php date in search.

For example, you can use moment.php library, which is a clone of moment.js library which is intented to fix problems among different systems, versions etc...

And to perform date calc in moment.php

For example

$m = new \Moment\Moment('2012-05-15T12:30:00', 'CET');
echo $m->addMinutes(60)->format(); // 2012-05-08T13:15:00+0200
Aleksandar Pavić
  • 3,143
  • 1
  • 34
  • 36