$date = new DateTime for older PHP versions - php

Using the code below I received an error and I found out that it has to do with my server not having the latest PHP running:
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT'.$a->metrics->duration.'S'));
The Error:
Fatal error: Call to undefined method DateTime::add()
The Question:
How would I achieve the above for a server that is running PHP 5.2.17 ?

You can make use of strtotime():
$date = strtotime ("2000-01-01");
$date = strtotime ("+900 seconds", $date); // adds 900 seconds to date

$start = new DateTime() ;
$start->modify( '+900 seconds' ) ;
var_dump( $start->format('h:i:s' ));
Using modify should still work for your version, enabling you to stick with DateTime, works for me on 5.2.6

Related

Time is converted wrongly on server

Time is not converted propely on server ,
I'm converting timestamp , on local host it works well, but on server it's earlier two hours ,
$ToConvert = 1570080669;
$dt = new DateTime();
$dt->setTimestamp($ToConvert);
$EndTime = $dt->format('m/d/Y H:i');
echo $EndTime;
on local host :
10/03/2019 07:31
on Server :
10/03/2019 05:31
what might be the problem?
The DateTime class in PHP has a method called "setTimezone" which expects an instance of DatetimeZone as an argument. Using your code as an example, you just need to add one extra line as follows:
$ToConvert = 1570080669;
$dt = new DateTime();
$dt->setTimestamp($ToConvert);
$dt->setTimezone(new DatetimeZone('Europe/London'));
$EndTime = $dt->format('m/d/Y H:i');
echo $EndTime;
You can change the argument when instantiating a new timezone as desired to suit your needs.
More information is on the php.net website:
https://www.php.net/manual/en/datetime.settimezone.php

php - Parse.com change createdAt Column timezone

I'm developing a PHP project and I'm using Parse SDK. What i want to do is adjust the time given by the Parse Database. It gives me time and date that 8 hours late to my timezone. Here's the code I'm using :
$query = new ParseQuery("TestObject");
$query->get("xWMyZ4YEGZ");
$dateTime = $query->getCreatedAt();
$sched = $dateTime->format("M d, Y - hA");
echo $sched;
How can i adjust it to specifically "GMT+8" TimeZone? Thanks!
You have to set the date_default_timezone_set before doing any thing as:
if(function_exists('date_default_timezone_set'))
date_default_timezone_set($timezone);
List of timezones are provided here...
Have a look at PHP date with TZ - See N.B.'s answer here is a code snippet he suggests (you may be able to use the parse date instead of the "now" parameter):
<?php
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');

How to add days to a date with a certain format? [duplicate]

This question already has answers here:
Add number of days to a date
(20 answers)
Closed 7 years ago.
I know this was asked before, but I looked at all those solutions and they don't work for me. Theirs start with a format that I'm not starting with, but even so I tried their solutions anyway and I kept getting a 1970 year as my end date.
So I have a start date in the format of mm-dd-YYYY, and I want to add 35 days to it to create an end date. The following is what I finally was able to make work, but it's inconsistent, or maybe I was wrong and it doesn't really work.
I convert the start date to YYYY-mm-dd because that's what i noticed works better with the strtotime function. I tried converting it differently but nothing worked except doing it the explode way.
So after format conversion then adding the days and converting format back, for some reason it adds like 49 days, even though I am specifying 35 days.
I don't know what else to try.
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate = $pieces[2]."-".$pieces[0]."-".$pieces[1];
$enddate = date('m-d-Y', strtotime($newdate. ' + 35 days'));
echo $enddate; //result is 10-01-2015 when it should be 09-17-2015
UPDATE
modified for my need. using variable as the start date.
$inputdate = new DateTime($startdate);
$inputdate->modify('+35 days');
$enddate = $inputdate->format('m-d-Y');
Get the following errors when the page with the code is ran:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character' in path\file.php on line 9002
Exception: DateTime::__construct(): Failed to parse time string (08-13-2015) at position 0 (0): Unexpected character in path\file.php on line 9002
9002 says this:
$inputdate = new DateTime($startdate);
DateTime with DateTime::modify() should do it, as shown.
$date = new DateTime('08-13-2015');
$date->modify('+35 days');
echo $date->format('m-d-Y');
But check your PHP version first, if it's below 5.1 you won't be able to use it and under 5.3 you'll face some minor bugs.
you can do it with mktime
$startdate = "08-13-2015";
$pieces = explode("-", $startdate);
$newdate2 = mktime(12, 0, 0, $pieces[0], $pieces[1] + 35, $pieces[2]);
$enddate2 = date('m-d-Y', $newdate2);
var_dump($enddate2); // 09-17-2015
you need to read this
http://php.net/manual/en/book.datetime.php
or use a date library like carbon
https://github.com/briannesbitt/Carbon

Error in PHP $date2 = $date1->format('Y-m-d')

I get the following error:
PHP Fatal error: Call to a member function format() on a non-object
in code:
$date = new DateTime();
$date1 = $date->modify('-6 months');
$date2 = $date1->format('Y-m-d');
I want to get this date of 6 months before from now and delete all entries in database which are earlier than this 6 months date:
$query = $conn->prepare("DELETE FROM files WHERE files.date < ?");
$query->bind_param('s', $date2);
$query->execute();
In MySQL "date" field is in files table of datatype "timestamp" whose value is "CURRENT_TIMESTAMP" stored by MySQL as default when a row is created.
This code get you 6 month ago from now:
date('Y-m-d', strtotime('now -6 month'))
EDIT:
and use DateTime:
echo (new DateTime('-6 months'))->format('Y-m-d');
try below code:
<?php
$date = new DateTime('-6 months');
echo $date2 = $date->format('Y-m-d');
?>
It appears you are using an outdated version of php.
Starting with php 5.3+ DateTime::modify returns the datetime object is was called upon prior to that null was returned.
You don't need to assign the result of modify to a new variable as it modifies the current object and does not return a new one.
To make it work on 5.2:
<?php
$date = new DateTime();
$date->modify('-6 months');
$dateS = $date->format('Y-m-d');
var_dump($dateS);
You should however update your php to a supported version.
PHP 5.4+ short-example:
$dateS = (new DateTime('-6 months'))->format('Y-m-d');
Seems like the call to
$date->modify('-6 months');
encounters an error and does not return a DateTime instance but probably false (see documentation).
Which PHP version are you using? I could not reproduce that error with the given example on PHP 5.5.9
Maybe you could just use the strtotime function
EDIT:
I took the Wayback Machine from Internet Archive and found that older versions of PHP ( i.e. 5.1.0) returned NULL instead of the DateTime object: see for yourself. In that case it seems like you apply the modification on your date directly so you need to change your code to
$date = new DateTime();
$date->modify('-6 months');
$dateString = $date->format('Y-m-d');
$query = $conn->prepare("DELETE FROM files WHERE files.date < ?");
$query->bind_param('s', $dateString);
$query->execute();

php check if specified time has expired

I am trying to compare the current datetime, with a datetime from the database using string, as the following:
$today = new DateTime("now");
$todayString = $today->format('Y-m-d H:i:s');
if($todayString >= $rows["PrioritizationDueDate"])
{...}
$todayString keeps giving me the time 7 hours earlier (i.e now its 11:03pm, its giving me 16:04).
More, is it better to compare this way, or should i compare using datetime objects?
$todayString keeps giving me the time 7 hours earlier
you have to setup a timezone for the DateTime object I believe.
is it better to compare this way
I doubt so.
The general way is to compare in the query, using SQL to do all date calculations and return only matching rows.
Set a correct timezone in the constructor to DateTime.
$today = new DateTime("now", new DateTimeZone('TimezoneString'));
Where TimezoneString is a valid timezone string.
Edit: For a more complete example using DateTime objects, I would use DateTime::diff in conjunction with DateTime::createFromFormat.
$rows["PrioritizationDueDate"] = '2011-11-20 10:30:00';
$today = new DateTime("now", new DateTimeZone('America/New_York'));
$row_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $rows["PrioritizationDueDate"], new DateTimeZone('America/New_York'));
if( $row_date->diff( $today)->format('%a') > 1)
{
echo 'The row timestamp is more than one day in the past from now.';
}
Demo
First set time zone using this function
date_default_timezone_set('UTC');
Then either you can use function strtotime() or get difference directly...

Categories