If else statement for PHP DateTime diff - php

I am using meta_box value (YmdHi) and current Date&time to print time difference. And this code work for me.
Now additionally i want to print Live when 2 hours left to start Event.
What mistake I 'm doing to print if or else currently this not work for me?
$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);
if ($sinceThen > 2 * HOUR_IN_SECONDS){
echo $sinceThen->d.'days';
echo $sinceThen->h.'hours';
echo $sinceThen->i.'minutes';
}
else{
echo 'LIVE';
}

$sinceThen is a DateInterval (that's what DateTime::diff() returns), so you're comparing a int with an object, which obviously gives you unexpected results. To get the difference in seconds, subtract both DateTime instances' timestamps (which you obtain with DateTime::getTimestamp()):
$then = date( get_post_meta( get_the_ID(), '_start_eventtimestamp', true ) ) ;
$then = new DateTime($then);
$now = new DateTime();
$sinceThen = $then->diff($now);
$sinceThenInSeconds = $then->getTimestamp() - $now->getTimestamp();
if ($sinceThenInSeconds > 2 * HOUR_IN_SECONDS){
echo $sinceThen->d.'days';
echo $sinceThen->h.'hours';
echo $sinceThen->i.'minutes';
}
else{
echo 'LIVE';
}

Related

Problem in checking when date and time has elapse using timezone

Am trying to create a date and time function to check if a given dateTime and timezone passed but my function is always returning true even when i put a future date.
I have below example class
<?php
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('M d, Y H:i:s', $startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
}
?>
Usage
Everything is returning true, my expectation is to return false if current time based on timezone has not yet elapse or return true when time has elapse or time is now
<?php
$job = new JobTimer();
//if($job->isDateTime("2019-05-02 12:00AM", "Asia/Kuala_Lumpur")){
//if($job->isDateTime("2021-05-02 12:00AM", "Asia/Kuala_Lumpur")){
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
?>
In your JobTimer class $startTime is false because your format for DateTime::createFromFormat() does not match the format of the date you are passing in as a parameter and causing it to fail.
M d, Y H:i:s matches May 02, 2020 12:00:00 which is not what you are passing to that class.
You should be using:
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
Working code:
class JobTimer{
public function __construct() {
}
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = \DateTime::createFromFormat('Y-m-d H:iA', $startOn, new \DateTimeZone($timezone));
return $nowTime >= $startTime;
}
}
$job = new JobTimer();
if($job->isDateTime("2020-05-02 12:00AM", "Asia/Kuala_Lumpur")){
echo "YES";
}else{
echo "NO";
}
Output:
NO
Demo
Change your function to this:
public function isDateTime($startOn, $timezone = "GMT"){
$nowTime = new \DateTime("NOW", new \DateTimeZone($timezone));
$startTime = new \DateTime($startOn, new \DateTimeZone($timezone));
return ($nowTime >= $startTime ? true : false);
}
Your argument passed to createFromFormat is wrong, and therefore not creating a DateTime correctly. You can just pass your $startOn and a DateTimeZone to create a instance of DateTime

PHP Conditional dates treatment - comparing times & dates

I want to make a condition for my function to work. This is the logic.
Booking closing is 12noon today.
If the current time is before closing time(say 11am today) then run function x. I need to set a time when booking closes and compare it to the current time.
$tz_object = new DateTimeZone('Africa/Kampala');
$datetime = new DateTime();
$datetime->setTimezone($tz_object);
$timeNow = $datetime->format('Y\-m\-d\ h:i:s');
$date = new DateTime();
$date->setTime(23,00);
$timeAllowed = $datetime->format('Y\-m\-d\ h:i:s');
if ($timeNow < $timeAllowed) {
function woo_add_cart_fee() {
global $woocommerce;
$woocommerce->cart->add_fee( __('Custom', 'woocommerce'), number_format(5) );
}
add_action( 'woocommerce_cart_calculate_fees', 'woo_add_cart_fee' );
}
Comparing DateTime objects is easy. You do not need to convert the date time to a string.
// time when booking closes
$bookclose = new \DateTime();
$bookclose->setTimezone(new DateTimeZone('Africa/Kampala'));
$bookclose->setTime(12,0,0);
// fake a time that the booking is being made for testing
$bookingtime = new \DateTime();
$bookingtime->setTimezone(new DateTimeZone('Africa/Kampala'));
$bookingtime->setTime(11,59,59);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
echo ' ALLOWED'.PHP_EOL;
} else {
echo ' NOT ALLOWED'.PHP_EOL;
}
$bookingtime->setTime(12,0,0);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
echo ' ALLOWED'.PHP_EOL;
} else {
echo ' NOT ALLOWED'.PHP_EOL;
}
$bookingtime->setTime(12,0,1);
echo 'Booking time is ' . $bookingtime->format('d/m/Y H:i:s');
if ($bookingtime < $bookclose) {
echo ' ALLOWED'.PHP_EOL;
} else {
echo ' NOT ALLOWED'.PHP_EOL;
}
RESULTS:
Booking time is 19/01/2017 11:59:59 ALLOWED
Booking time is 19/01/2017 12:00:00 NOT ALLOWED
Booking time is 19/01/2017 12:00:01 NOT ALLOWED

PHP if based on current system date

Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg

How do i know if a time is elapsed/expired in php?

Here's the scenario
I would like to know if a date like '2011-03-04' and time like '17:06:00' in a specific TimeZones like 'IST/PDT/CDT' is elapsed by using php?
Is there any function available to check this
$strDate = '2011-03-04 17:06:00';
$TZ = 'IST';
$strDate = '2011-02-01 11:16:30';
$TZ = 'CDT';
$strDate = '2010-08-04 07:20:00';
$TZ = 'IST';
$strDate = '2011-02-27 09:55:00';
$TZ = 'PST';
I've tried/searched all over the net but no joy, please help
Yeah i tried it using DateTime but it doesnt work for me.. My server is in IST TimeZone
$date = new DateTime('2011-03-04 17:06:00');
$date->setTimeZone(new DateTimeZone("PST"));
$newtime = $date->getTimestamp();
$time = time();
if ($time > $usertime)
echo 'time passed';
else
echo 'time NOT passed';
Thanks to tobyS but it too falied
$elapsedTime = new DateTime(
'2011-03-04 17:00:00', // I set it to 5PM. Now the time is 5:45 PM here in INDIA
new DateTimeZone( 'IST' )
);
$elapsedInt = $elapsedTime->diff( new DateTime() );
echo ( $elapsedInt->invert ? 'Future' : 'Past' ) . "\n";
You can create a DateTime object from your time data and use its diff() method against the current time.
Example code:
<?php
$elapsedTime = new DateTime(
'2010-08-04 07:20:00',
new DateTimeZone( 'IST' )
);
$notElapsedTime = new DateTime(
'2012-08-04 07:20:00',
new DateTimeZone( 'IST' )
);
$elapsedInt = $elapsedTime->diff( new DateTime() );
echo ( $elapsedInt->invert ? 'Future' : 'Past' ) . "\n";
$notElapsedInt = $notElapsedTime->diff( new DateTime() );
echo ( $notElapsedInt->invert ? 'Future' : 'Past' ) . "\n";
?>
PHP doesn't understand those timezones:
$timezone = 'America/New_York';
$date = new DateTime($strDate, new DateTimeZone($timezone));

Convert time and date from one time zone to another in PHP

Basically what I need is an script that, when provided with a time and a timezone can return the time in another time zone.
My main issues are:
Where to get the time offset from GMT from - is there a public database available for this?
How to also take into consideration the daylight saving time (DST) differences as well.
How to nicely wrap it all up inside an PHP class - or is there such a class already available?
<?php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
The above examples will output:
2000-01-01 00:00:00+12:00
2000-01-01 01:45:00+13:45
found on DateTime Manual on php.net
EDIT:
Like Pekka said: The DateTime class exists from 5.2 on and there you first have to find out which of the methods are realy implemented and which one only exist from 5.3 on.
try this, it might help :)
function converToTz($time="",$toTz='',$fromTz='')
{
// timezone by php friendly values
$date = new DateTime($time, new DateTimeZone($fromTz));
$date->setTimezone(new DateTimeZone($toTz));
$time= $date->format('Y-m-d H:i:s');
return $time;
}
A bit description:
The function takes 3 inputs, time to convert, timezone to convert to, current timezone and returns the output in the specified format.
I know its late. For anyone who would want simple function to convert utc to any local time zone
function UTCTimeToLocalTime($time, $tz = '', $FromDateFormat = 'Y-m-d H:i:s', $ToDateFormat = 'Y-m-d H:i:s')
{
if ($tz == '')
$tz = date_default_timezone_get();
$utc_datetime = DateTime::createFromFormat($FromDateFormat, $time, new
DateTimeZone('UTC'));
$local_datetime = $utc_datetime;
$local_datetime->setTimeZone(new DateTimeZone($tz));
return $local_datetime->format($ToDateFormat);
}
echo UTCTimeToLocalTime('2015-07-01 13:30:00','America/Denver');
To convert from the given timezone to the desired timezone, we just have to add/subtract the difference of timezones (in SECONDS) to given timezone.
$my_timestamp = strtotime("2020-09-22 14:07:26");
/*
Convert timezones difference into seconds
from -7:00 to +5:30 have 12hrs and 30min difference
So in seconds, 12.5*60*60 is equaled to 45000 seconds
*/
$time_zone_difference = 45000;
//Use date function to get datetime in your desired formate
echo date("Y-m-d h:i:sa", $my_timestamp + time_zone_difference );
or we can write it like
Below given functions are for additional help.
Convert timezone differences in seconds, (which you can hardcode, if it is fixed throught the project):
function timezoneDifferenceInSec( $source_timezone, $required_timezone){
$a = explode(":",$source_timezone);
$b = explode(":",$required_timezone);
$c = (intval($a[0])*60+intval($a[1]))*60;
$d = (intval($b[0])*60+intval($b[1]))*60;
$diffsec =0;
if($c < $d)
$diffsec = $d-$c;
else
$diffsec = $c-$d;
return $diffsec;
}
//function call
$differenc = timezoneDifferenceInSec("-07:00", "+05:30");
Function to convert DateTime into required Timezone (if difference is known):
//datetime in String and timezone_differe is in int
function convertTimezone( $source_date_time, $timezone_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezone_diff_in_sec);
}
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);
Function to convert DateTime into required Timezone (if difference in seconds among the timezones is known):
example: Timestamp give is "2020-09-22 14:07:26".
Timezones difference in seconds id 4500; //ie from -07:00 to +05:30
// timestamp as in String and timezones_diff_in_sec is in int
function convertTimezone( $timestamp, $timezones_diff_in_sec){
return date("Y-m-d h:i:sa", strtotime($source_date_time) + $timezones_diff_in_sec);
}
Function call (
//function call
$timestamp = "2020-09-22 14:07:26";
$timezone_difference = 4500; //ie from -07:00 to +05:30
echo convertTimezone( $timestamp, $timezone_difference);
Here i use this function for converting datetime into another timezone.
For best result if you convert your datetime into utc timezone and then convert into required timezone then it is better result for it.
function ConvertTimezoneToAnotherTimezone($time, $currentTimezone, $timezoneRequired) {
$dayLightFlag = false;
$dayLgtSecCurrent = $dayLgtSecReq = 0;
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d H:i:s");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecCurrent = -3600;
// }
date_default_timezone_set("GMT");
$gmt = date("Y-m-d H:i:s ");
$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d H:i:s ");
/* Uncomment if daylight is required */
// $daylight_flag = date("I", strtotime($time));
// if ($daylight_flag == 1) {
// $dayLightFlag = true;
// $dayLgtSecReq = +3600;
// }
date_default_timezone_set($system_timezone);
$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));
$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
if ($dayLightFlag) {
$final_diff = $dayLgtSecCurrent + $dayLgtSecReq;
$date->modify("$final_diff seconds");
}
$timestamp = $date->format("Y-m-d H:i:s ");
return $timestamp;
}
Thank You.

Categories