DateTime object declaration breaks script on PHP 5.4.16 - php

While editing the php file it shows DateTime is not a valid method, plus when I try to use this it stops loading the rest of the page, do I have to implement something?
My goal is to check either if the difference between those variables is more than 3 minutes.
Can I output the difference just in minutes?
$arr["etime"] comes from a mysql query in the format of Y-m-d H:i:s.
$etime = $arr["etime"];
$datenow = date('Y-m-d H:i:s');
$datetimenow = new DateTime($datenow);
$datetimee = new DateTime($etime);
$datedifference = $datetimee->diff($datetimenow);
echo $datedifference->format("%H:%I:%S");
If I just put $date = new DateTime('2000-01-01'); it doesn't load the rest of the page after this.
If I put $datetimenow = new DateTime(); the rest of the page won't load.
Using exception handling, I received:
PHP Fatal error: Uncaught exception 'Exception'
with message:
'DateTime::__construct(): It is not safe to rely on the system's
timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone.'

You will only need to check the output object values generated from diff(): (Demo)
$etime = '2017-07-10 16:59:04';
$timezone=new DateTimeZone("Australia/Melbourne"); // declare whatever your timezone is
$datetimee=new DateTime($etime,$timezone); // resultset datetime
$datetimenow=new DateTime("now",$timezone); // current datetime
$diff=$datetimee->diff($datetimenow);
//var_export($diff);
if($diff->i>=3 ||$diff->h>0 || $diff->d>0 || $diff->m>0 || $diff->y>0){
echo "Difference is 3 minutes or more";
}else{
echo "Difference is not yet 3 minutes";
}
If you are still experiencing issues with the DateTime class, it may be time to revert to good-ol' strtotime(). It provides a much simpler bit of code anyhow:
if(strtotime('now')-strtotime($etime)>179){ // assuming now is always bigger than etime
echo "Difference is 3 minutes or more";
}else{
echo "Difference is not yet 3 minutes";
}

Related

Calculating time passed since a textual date/time value [duplicate]

This question already has answers here:
How to calculate the difference between two dates using PHP?
(34 answers)
Closed 5 years ago.
I have a database from which I extract this date/time value: 2018-01-19 09:50:54
I want to print how many hours and minutes passed since that date, with regard to current server time:
I try this code:
$prev_date = "2018-01-19 09:50:54" // extracted from DB
$date_now = date("Y-m-d H:i:s"); // 24-hour date-time, matches DB format
$interval = $prev_date->diff($date_now); // I saw this on another thread
echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";
I get:
Fatal error: Call to a member function diff() on a non-object (on the
$interval=.... line )
I guess it is some kind of formatting problem, how do I fix that?
$prev_date is not a object. You need to transform to a DateTime object to use diff. Also, date() will return a string, you must use a DateTime object for this to be able to use diff function.
$prev_date = DateTime::createFromFormat('Y-m-d H:i:s', '2018-01-19 09:50:54');
$date_now = new DateTime(); // 24-hour date-time, matches DB format
$interval = $prev_date->diff($date_now); // I saw this on another thread
echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes";

Laravel 5.3 - Carbon Date - UTC offset get timezone name

I am trying to get a timezone name from a UTC offset in Laravel 5.3 using Carbon. Code listed below any help would be much appreciated.
/* current code iteration */
$utcOffset = -5;
$timezone = Carbon::now($utcOffset)->timezone->getName();
echo $timezone;
// Result: -05:00
// Expected Result: EST
/* tried code */
$timezone = Carbon::now($utcOffset)->tzName;
// Result: -05:00
/* What I used prior to Carbon */
$timezone = timezone_name_from_abbr(null, $utcOffset * 3600, TRUE);
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone($timezone));
$timezone = $dateTime->format('T');'
What am I missing? I feel daft..
Preface:
The accepted answer works in most cases but as mentioned in the user contributed notes area of timezone_name_from_abbr(), there are issues with using the function, like returning false instead of actual timezone and returning a "historical" (i.e. deprecated) timezone identifier rather than the current standard one for a given location. Which are still valid to this date.
Also, the original code returns the value as expected, as long as you know that as per Carbon docs, if you look at https://carbon.nesbot.com/docs/#api-timezone
the original name of the timezone (can be region name or offset string):
One more thing to note here is that, it is considered not reliable to derive timezone off of offset value as it does not take into consideration the DST observed periods offset.
So, this all to actually say that deriving timezone off of offset is not always possible.
Answer:
But since the OP mentioned Carbon and timezone based on offset, as per the Carbon docs as of now, the answer should be
$date = Carbon::now('-5');
echo $date->tzName;
Tried updating Carbon to no evail ended up using the old datetime class.
$timezone = timezone_name_from_abbr(null, $utcOffset * 3600, TRUE);
$dateTime = new DateTime();
$dateTime->setTimeZone(new DateTimeZone($timezone));
$timezone = $dateTime->format('T');
In a new Carbon it is timezoneName property;
$now = Carbon::now(-5);
echo $now->timezoneName;
//or
echo $now->timezone->getName();
This works for me:
$now = Carbon::now(-5);
echo $now->timezone;
// prints 'America/Chicago'

strtotime() time zone warning. Storing a simple Unix Timestamp in a MySQL database with UTC Timezone [duplicate]

This question already has answers here:
"date(): It is not safe to rely on the system's timezone settings..."
(25 answers)
Closed 8 years ago.
Here is the warning I get:
PHP Warning: strtotime(): It is not safe to rely on the system's timezone settings. You are required to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Chicago' for 'CST/-6.0/no DST' instead in /data1/home/spaceweather/Scripts/casesFiles_InsertIntoDataBase.php on line 38
Here is my code for what I'm using to set my timezone in my script.
I'm trying to eliminate the PHP Warning and specify it as UTC to strtotime() NOT my default to my time zone on my system. (P.S. Go Blackhawks!)
$year = substr($filePath[$row], -17,4); //where this outputs a simple year 'CCYY'
$day = $days2[$days2keys[$i]]; //where this provides the day of year
$format = 'Y-z'; //specifying what format i'm creating the datetime with
$date = $year . '-' . $day; //formatting the strings to the above $format
$timezone = new DateTimeZone('UTC'); //specify the timezone
$fileDateStore[$row] = DateTime::createFromFormat($format, $date, $timezone); //create the DateTime object
$fileDateString[$row] = date_format($fileDateStore[$row],"Y-m-d".PHP_EOL); //format it so strtotime() can read it
$fileDate[$row] = strtotime($fileDateString[$row]); //finally create the Unix Timestamp for the date.
And then later on I store this into the database using the following code:
//connect to the database
$con=mysqli_connect("server","database","username","password");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
for($j = 1; $j < $numrows; $j++) {
$date = $fileDate[$j];
mysqli_query($con,"INSERT INTO tablename (fileDate)
VALUES (".$date.")");
}
mysqli_close($con);
echo "task finished and database connection closed.".PHP_EOL;
Edit your php.inifile and add something similar to
date.timezone = America/Chicago
Alternatively, you can use the date_default_timezone_set() function in your code:
date_default_timezone_set('America/Chicago');
For a list of valid values, check out http://php.net/manual/en/timezones.php

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

Changing current user timezone based on server UTC offset and user UTC offset

im writing a twitter web service in php. When a user signs in, i receive this node:
<utc_offset>-18000</utc_offset>
I have to change the script's timezone so that it adapts to the user's real timezone. The only php function i have found for this is: date_default_timezone_set($timezone_identifier) but it won't let me use -18000 as a the $timezone_identifier parameter.
So, how can i change the current user timezone based on two values: Server UTC offset and User UTC offset
BTW, this is how i'm getting the server UTC offset value:
$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
Any ideas? Thanks!
To get current server time
date_default_timezone_set(date_default_timezone_get());
echo date('Y-m-d H:i:s', time());
Output for Europe/Paris (my server settings; UTC+2)
2011-04-12 20:39:43
To get user's time by offset
$user_offset = '-18000';
date_default_timezone_set('UTC');
$diff = "$user_offset seconds";
if ((substr($diff,0,1) != '+') && (substr($diff,0,1) != '-')) $diff = '+' . $diff;
$usertime = strtotime($diff, time());
echo date('Y-m-d H:i:s', $usertime);
Output UTC-5 (Ecuador -> Quito time NO DST), php timezone identifier 'America/Guayaquil'.
2011-04-12 13:39:43
PHP.net manual:
Timezone offset in seconds. The offset
for timezones west of UTC is always
negative, and for those east of UTC is
always positive. (-43200 through
50400)
The date_default_timezone... functions expect a string giving something like "Africa/Luanda" or whatever.
I suggest programmatically searching through the timezone database for a matching offset. If I recall correctly, those are in minutes from UTC, so you should divide the offset you are given by 60.

Categories