I want to get the date of yesterday of the current date in a specifc time zone.
I tried like this, but it is not working:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$yesterday = $date->modify( '-1 day' );
$yesterday = $yesterday->format('Y-m-d');
I am still getting today's date.
This problem, according to the documentation for the modify() method, seems to entirely depend on which version of php you're using. In this case, method chaining(which is what you're attempting to do is called), is only available on php version 5.3.0 and up, according to the changelog on the previously linked docs.
That in mind, it explains why your code didn't work, and #Deryck's did. If you ever do upgrade your php version, or get your host to upgrade it, you could likely reduce those three lines to two:
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date = $date->modify( '-1 day' )->format('Y-m-d');
Not much of an improvement, I realize, but there's your reason for why it failed to work.
Below are two of the methods I see of getting around this; one is creation of a class.. which seems like overkill to me unless this is apart of something grander... the other is a creation of a function. Both shove the extra lines into something that takes up less space, in a sense.
class DT {
private $now; //can be null
private $timezone; //DateTimeZone object
public function __construct($tz_str, $now = NULL) {
$this->now = $now;
$this->timezone = new DateTimeZone($tz_str);;
}
public function mod($mod,$format) {
$dt = new DateTime($this->now, $this->timezone);
$dt->modify($mod);
return $dt->format($format);
}
}
function mod_formatted_zone($tz_str, $mod, $format, $now = NULL) {
$timezone = new DateTimeZone($tz_str);
$dt = new DateTime($now,$timezone);
$dt->modify($mod);
return $dt->format($format);
}
The use of either is simple; in the case of the class, it'd be something like..
$dt = new DT('Pacific/Wake');
echo $dt->mod('-1 day', 'Y-m-d');
While in the case of the function, it'd simply be..
echo mod_formatted_zone('Pacific/Wake', '-1 day', 'Y-m-d');
Seems to work once you don't re-assign the $date variable unnecessarily. See below:
<?php
$date = new DateTime(NULL, new DateTimeZone('Pacific/Wake'));
$date->modify("-1 day");
$date = $date->format("Y-m-d");
// echo $date; // just in case you wanna echo - ya dig
?>
View demo
FYI:
Wake Island Time Zone (UTC+12:00)
Which means 1 day before is actually today (for me at least, on the western hemisphere).
I want to get the date of yesterday of the current date in a specifc time zone.
You can specify relative dates in the DateTime constructor. This will work for you:-
$yesterday = new DateTime('- 1 day', new DateTimeZone('Pacific/Wake'));
var_dump($yesterday);
Proof!.
Related
Although my question seems can be found the solution on the internet easily. But I've already tried but it's not working.
I've already followed https://www.php.net/manual/en/datetime.diff.php Example #2 DateTime object comparison
or another solution like https://thevaluable.dev/php-datetime-create-compare-format/ Comparing DateTime Objects
But it is still not working.
Here is my code,
$end_time = new DateTime('2020-04-05 23:59:00');
$now = new DateTime('now');
if( $now > $end_time ){
echo 'expired!';
}
It throws the error
Object of class DateTime could not be converted to string.
Edited
I'm using PHP 7.1.23
Here is the solution for your problem. First you have to convert them into Strings then you can use them. I have changed the input date just to show you the result of if condition.
Select your City for time zone First
date_default_timezone_set('Asia/Karachi');
Your Inputs
$input_time = new DateTime('2020-04-01 23:59:00');
$now = new DateTime('now');
Convert them to string
$input_time = $input_time->format('Y-m-d H:i:s');
$now = $now->format('Y-m-d H:i:s');
The result
if( $now > $input_time )
{
echo 'expired!'. '<br>';
}
If it doesn't need to be an actual DateTime object, you could use times instead, which will then compare the same as an integer would.
Eg
$end_time = strtotime('2020-04-05 23:59:00');
$now = time();
if( $now > $end_time ) {
echo 'expired!';
}
I'm using the PHP DateTime class to generate a date for a custom licensing system. While I'm debugging it, I've noted that the date time are always wrong, it will be 5-dec-2018 but now we are in November, and this date will be the same also for the expiration_date.
How i can fix this issue? I need to add 30 days to the start date of the trial period.
Here is the code.
class Activator {
private $uuid;
private $keygen;
private $licence_code;
public static function generateLicence($uuid) {
if (!file_exists(ABSPATH.'/DataStorage/.licence')) {
$start_date = new DateTime();
$time_zone = $start_date->setTimezone(new DateTimeZone('Europe/Rome'));
$trial_date = $start_date->add(new DateInterval('P30D'));
$end_date = $trial_date->format('d-M-Y');
$machine_uuid = bin2hex($uuid);
$licence_code = base64_encode($machine_uuid);
$licence_file = array(
'uuid' => $machine_uuid,
'activation_date' => $time_zone->format('d-M-Y'),
#'trial_version' => true,
#'expire_date' => $end_date,
#'licence_code' => $licence_code
);
$w = file_put_contents(ABSPATH.'/DataStorage/.licence', json_encode($licence_file));
echo $w;
}
}
This is the expected behavior, as you add() to the date (by doing $start_date->add(...) - this modifies the original object $start_date.
You can solve this a few different ways, although the easiest way is just to create a new instance entirely with the 30 days added directly in the construct. You can also set the timezone as the second parameter of new DateTime().
$timezone = new DateTimeZone('Europe/Rome');
$start_date = new DateTime("now", $timezone);
$trial_date = new DateTime("+30 days", $timezone);
PHP.net on new DateTime()
PHP.net on DateTime::add()
See this live demo.
this is what I have got:
$_SESSION["chosen_exam_start_time"] = new DateTime();
$schedule_date = $_SESSION["chosen_exam_start_time"];
$schedule_date->setTimeZone(new DateTimeZone('Europe/London'));
$triggerOn = $schedule_date->format('Y-m-d H:i:s');
so I have a date passed within the session called "chosen_exam_start_time".
Now what I am struggling to do is add on $triggerOn.
So currently if I do
die(var_dump($triggerOn));
I get :
string(19) "2016-03-28 17:17:57"
What I want to do is if I have another variable which tells me a value like 10, how would I be able to add that value on to the $triggerOn. So that it will be:
string(19) "2016-03-28 17:27:57"
What I have done up to now is :
$_SESSION["chosen_exam_start_time"] = new DateTime();
$schedule_date = $_SESSION["chosen_exam_start_time"];
$schedule_date->setTimeZone(new DateTimeZone('Europe/London'));
$triggerOn = $schedule_date->format('Y-m-d H:i:s');
$value = 10;
$triggerOn->modify((int) $value.' minute');
die(var_dump($triggerOn));
However this die is not printing anything out now
I doesn't make sense to make any sort of calculation using strings. Just imagine you had this:
$price = 'Thirty five point nine';
$discount = 'Twenty percent';
... and you wanted to apply the discount ;-)
If your current architecture makes it impossible to keep the original DateTime object (I don't know, I don't have enough information for that) you'd better create a new one:
<?php
$triggerOn = '2016-03-28 17:17:57';
$minutes_to_add = 10;
$triggerOnDateTime = new DateTime($triggerOn, new DateTimeZone('Europe/London'));
$triggerOnDateTime->modify( sprintf('%d minutes', $minutes_to_add) );
$triggerOn = $triggerOnDateTime->format('Y-m-d H:i:s');
You are looking for the modify function on a datetime object.
$trigger->modify((int) $value.' minute');
Note I just pulled this from the Carbon Library, which is a very useful wrapper for DateTime giving you a good bit of syntactic sugar such as:
$trigger->addMinutes(10);
I have on function which passing some parameter the like
everyWeekOn("Mon",11,19,00)
I want to compute the difference between the current day (e.g. 'Fri')
and passed parameter day i.e. Mon.
The output should be:
The difference between Mon and Fri is 3
I tried it like this
$_dt = new DateTime();
error_log('$_dt date'. $_dt->format('d'));
error_log('$_dt year'. $_dt->format('Y'));
error_log('$_dt month'. $_dt->format('m'));
But know I don't know what to do next to get the difference between the two days.
Note that this question is different from How to calculate the difference between two dates using PHP? because I only have a day and not a complete date.
Just implement DateTime class in conjunction with ->diff method:
function everyWeekOn($day) {
$today = new DateTime;
$next = DateTime::createFromFormat('D', $day);
$diff = $next->diff($today);
return "The difference between {$next->format('l')} and {$today->format('l')} is {$diff->days}";
}
echo everyWeekOn('Mon');
$date = new DateTime('2015-01-01 12:00:00');
$difference = $date->diff(new DateTime());
echo $difference->days.' days <br>';
You can find no. of days in two days by using this code
<?php
$today = time();
$chkdate = strtotime("16-04-2015");
$date = $today - $chkdate;
echo floor($date/(60*60*24));
?>
Please use this may this help you
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...