DEV Community

Cover image for Fetch Timestamp Of Youtube Video / Convert It (PHP + CSS)
aryaziai
aryaziai

Posted on • Updated on

Fetch Timestamp Of Youtube Video / Convert It (PHP + CSS)

UX Advantage

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.

Before

After

Let's Get Started

Endpoint:

https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=[VIDEO_ID]&key=[API KEY]

Example Video ID: GW4f9HY-6Ng

API Key: If you don't have a key, please sign up at Google Developers Console and enable the Youtube Data API v3 to obtain your free key.

Fetch Request

$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

Convert Output

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 function to help us convert PT1H9M38S into something a little more readable.

One More Step

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.

Remove Zero's

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

Putting It All Together

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');
    }
}

CSS

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.

.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.

Top comments (0)