Fetch Timestamp Of Youtube Video / Convert It (PHP + CSS)
Tags: youtube, fetch, php
Published: 2020-06-23 02:27:14

<h3>UX Advantage</h3>
When developing a website, specifically a dynamic blog, the question of "How do I engage my users and increase clicks" comes up quite often. There isn't one simple solution, however, there are certain details that play a role in the user's decision to engage with the content. I recently noticed a pattern in my decision-making process when browsing Youtube. I would first look at the thumbnail of a video, read the title, and lastly, examine the timestamp of the video. All three factors are considered in a split second before deciding whether to click the video or continue scrolling. If the video thumbnail and title are interesting but the duration is very short/long, chances are that I won't click. Seeing the timestamp before clicking on a video, allows me to make the decision of whether I want to invest X amount of time or not. This detail allows me to feel more in control of my time, thus creating a more positive user experience. 

One of my blog sites contains many Youtube videos, each blog post containing one video. I created a  fetch request to import the timestamp of each video, convert it to a readable format, and output the result on each video thumbnail.

<h4>Before</h4>
<img src="https://dev-to-uploads.s3.amazonaws.com/i/ee4j6mtqtxxg1e5hv0nb.png">
<h4>After</h4>
<img src="https://dev-to-uploads.s3.amazonaws.com/i/dmacunig9czd1i6flajo.png">

<h3>Let's Get Started</h3>
<b>Endpoint:</b> ```https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=[VIDEO_ID]&key=[API KEY]```
<b>Example Video ID:</b> GW4f9HY-6Ng

<b>API Key:</b> If you don't have a key, please sign up at <a href="https://console.developers.google.com/">Google Developers Console</a> and enable the Youtube Data API v3 to obtain your free key.
<img align="left" src="https://dev-to-uploads.s3.amazonaws.com/i/uoa4nxnaj3a9gq9wjkjy.png">

<h3>Fetch Request</h3>
``` php 
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$VIDEO_ID&key=$API_KEY");
$duration_key = json_decode($dur, true);
$duration = $duration_key['items'][0]['contentDetails']['duration'];

// Output: PT1H9M38S
```

<h3>Convert Output</h3>
``` php
function covtime($youtube_time){
    $start = new DateTime('@0'); // Unix epoch
    $start->add(new DateInterval($youtube_time));
    return $start->format('H:i:s');
}   

echo covtime('PT1H9M38S');

// Output: 01:09:38
```
Thanks to Amal Murali for writing this neat <a href="https://stackoverflow.com/questions/24393230/convert-youtube-api-v3-video-duration-in-php/24393769#24393769">function</a> to help us convert PT1H9M38S into something a little more readable. 
<h3>One More Step</h3>
The current function will show a lot of zero's in the timestamp, which may feel too technical for the user. ie. 9-minute video will appear 00:09:00. I wanted to take one extra step to make the output more user-friendly by conditionally removing the zero's from the output.

<h3>Remove Zero's</h3>
``` php
function covtime($youtube_time){
    $start = new DateTime('@0');
    $start->add(new DateInterval($youtube_time));
    
    if ($start->format('H') != 00) { // if hours exist, return entire duration
          if ($start->format('H')[0] == 0) { // if less than 10 hours, eliminate first zero
           $eliminate_zero = substr($start->format('H:i:s'),1);
          return $eliminate_zero;
          }
          else {
            return $start->format('H:i:s');
          }
    }
    elseif ($start->format('i')[0] == 0) {
            $eliminate_zero = substr($start->format('i:s'),1);
            return $eliminate_zero;
        }
    else {
    return $start->format('i:s');
    }
}

echo covtime('PT1H9M38S');

// Output: 1:09:38
```
<h3> Putting It All Together</h3>
``` php
function video_set_duration() {
$vidId = ''; // Input Video ID
$key = ''; // Input API Key

$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidId&key=$key");
$duration_key = json_decode($dur, true);
$duration = $duration_key['items'][0]['contentDetails']['duration'];

$start = new DateTime('@0');
$start->add(new DateInterval($duration));

    if ($start->format('H') != 00) { // if hours exist, return entire duration
          if ($start->format('H')[0] == 0) { // if less than 10 hours, eliminate first zero
           $eliminate_zero = substr($start->format('H:i:s'),1);
          return $eliminate_zero;
          }
          else {
            return $start->format('H:i:s');
          }
    }
    elseif ($start->format('i')[0] == 0) {
            $eliminate_zero = substr($start->format('i:s'),1);
            return $eliminate_zero;
        }
    else {
    return $start->format('i:s');
    }
}
```
<h3>CSS</h3>
If you'd like the timestamp overlaid on top of the video thumbnail, be sure to include the timestamp within the same div as the thumbnail. Below is the CSS that I'm using to render the timestamp in the bottom right corner of the thumbnail.

``` css
.duration {
    position: absolute;
    background: rgba(0,0,0,.8392156862745098);
    color: #fff;
    font-weight: 600;
    z-index: 1;
    bottom: 4px;
    right: 5px;
    padding: 0 3px;
    font-size: 11.5px;
    letter-spacing: .3px;
}
```

Hope you enjoyed this tutorial, please let me know if you have any questions.