0

I am using the PHP AWS SDK for getting all the running instances in my account. I used the following API:

$this->ec2Client = Ec2Client::factory(array(
            'profile' => AWS_PROFILE, //contains my credentials
            'region' => 'ap-northeast-1',
            'version' => 'latest',
        ));

$result = $this->ec2Client->DescribeInstances(array(
            'Filters' => array(
                array('Name' => 'instance-state-name', 'Values' => array('running')),
            )
        ));

I can get all the running instances with the LaunchTimeand the AvailabilityZone information.

The values for them are 2014-10-31T10:58:35+00:00 and ap-northeast-1a respectively.

Based on this information, I want to calculate the running time in minutes. What is the correct way to do this?

kosta
  • 4,302
  • 10
  • 50
  • 104

2 Answers2

0

The value provided for each instance's LaunchTime should be an instance of DateTime. You can get how long an instance has been running by getting the difference between LaunchTime and another DateTime instance:

$interval = $launchTime->diff(new \DateTime('now'), true);
giaour
  • 3,878
  • 2
  • 25
  • 27
  • Since the EC2 client and other instances could be running in different AZs, do we need to consider the timezone? – kosta Apr 05 '16 at 06:15
  • No. `DateTime` objects take timezone into account when calculating a diff, and the value returned from EC2's API is an integer (epoch) timestamp. – giaour Apr 05 '16 at 06:19
  • ok, but the vaue returned for `launchTime` is `string` and I need the result in minutes. So I tried the following: `$launch_time = new DateTime($instance["LaunchTime"]);` `$launch_time->diff(new \DateTime('now'), true)` Now `echo $launch_time` produces hours, minutes, days separately. Should I then manually convert to minutes? – kosta Apr 05 '16 at 06:42
  • Ah, didn't realize you were using v2. LaunchTime is a `DateTime` in v3 and a string in v2, but the string can be passed to `DateTime`'s constructor. `DateTime::diff` will return a `DateInterval` object, which can be formatted as per http://php.net/manual/en/dateinterval.format.php – giaour Apr 05 '16 at 15:47
0

I solved it using the following in v3:

function interval_in_minutes($start_time){
        return round(abs($start_time->getTimestamp() -
            (new \DateTime)->getTimestamp()) / 60);
    }

$running_time = interval_in_minutes($instance["LaunchTime"]);
kosta
  • 4,302
  • 10
  • 50
  • 104