0

Here i am doing remaining count town time, Like suppose event going to start 2018-04-18 04:30 PM,Suppose current time is 2018-04-18 04:10 PM means i want to display like 20 Minutes left,I witten the code but it is showing wrong result

My PHP code:

    <?php
date_default_timezone_set('UTC');
date_default_timezone_set('Asia/Kolkata');

    function timeAgo($logintime)
        {
        $start_date = new DateTime($logintime);
        $since_start = $start_date->diff(new DateTime(date("Y-m-d h:i:s")));//2018-04-18 04:10 PM

        if( intval($since_start->format('%Y') ) >= 1){
             $timeago = $since_start->format('%Y years');
        }
        else if(intval($since_start->format('%m')) >= 1){
             $timeago = $since_start->format('%m months ');
        }
        else if(intval($since_start->format('%a')) >= 1){
             $timeago = $since_start->format('%a days ');
        }
        else if(intval($since_start->format('%h')) >= 1){
             $timeago = $since_start->format('%h hours ');    
        }
        else if(intval($since_start->format('%i')) >= 1){
             $timeago = $since_start->format('%i minutes ');  
        }
        else if(intval($since_start->format('%s')) >= 1){
             $timeago = $since_start->format('%s seconds '); 
        }
          return $timeago;  
        }

    echo timeAgo('2018-04-18 04:30 PM');
?>

I am getting result like this

12 hours

My Expected output is

20 Minutes left

Ivar
  • 6,138
  • 12
  • 49
  • 61
Sagu K
  • 99
  • 1
  • 6
  • Possible duplicate of [How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Philipp Maurer Apr 18 '18 at 11:07

1 Answers1

-1

Your just give the now DateTime only. You don't want to declare the time format. And you just use this time zone only date_default_timezone_set('Asia/Kolkata');. Here is code:

date_default_timezone_set('Asia/Kolkata');
   function timeAgo($logintime)
        {
        $start_date = new DateTime($logintime);
        $since_start = new DateTime();
        $interval = $since_start->diff($start_date);

        $timeago = $interval->format("%a days, %h hours, %i minutes, %s seconds");
        if($since_start < $start_date){
            return $timeago. ' ago'; 
        }else{
            return 'This Event Passed'; 
        }

        }

    echo timeAgo('2018-04-19 05:50 PM');

Out put:

1 days, 0 hours, 56 minutes, 28 seconds ago

Nawin
  • 1,653
  • 2
  • 14
  • 23
  • Why do you keep this part in the answer? `date_default_timezone_set('UTC'); date_default_timezone_set('Asia/Kolkata');` you must know the second will overwrite the first one? – Andreas Apr 18 '18 at 11:11
  • @ Andreas, I want to display day and Hour, in our case answer should come like this `0 days and 11 minutes ` how can achive this – Sagu K Apr 18 '18 at 11:18
  • Answer Edited @SaguK Please Check Now – Nawin Apr 18 '18 at 11:24